How to Find the Number of Times If or Else Code Has Executed

How can I count how many times this program has been executed in Python?

how can i count how many time program has been executed in python

The only way I can think of to satisfy your problem as you've described it rather then running your function N times is something like this:

Example:

from __future__ import print_function


import atexit
from os import path
from json import dumps, loads


def read_counter():
return loads(open("counter.json", "r").read()) + 1 if path.exists("counter.json") else 0


def write_counter():
with open("counter.json", "w") as f:
f.write(dumps(counter))


counter = read_counter()
atexit.register(write_counter)


def main():
print("I have been run {} times".format(counter))


if __name__ == "__main__":
main()

Sample Run(s):

$ python foo.py
I have been run 1 times
$ python foo.py
I have been run 2 times
$ python foo.py
I have been run 3 times

However I must point out that this is not a very good way to "measure" the performance of a program or the functions you've written. You should be looking at things like hotshot or timeit or running your function internally a number of times and measuring the "right things".

How to count how many times a loop has been executed? c++

#include <iostream>
using namespace std;

int main()
{

int n, i, k;
int counter = 0;
bool isprime;


cout << "Enter a positive integer n: ";

cin >> n;

for(int k = 2; k <= n; k++)
{
isprime = true;

for(int i = 2; i <= k - 1; i++)
if(k%i == 0)
{
isprime = false;
}

if(isprime)
{
cout << k << "\t";
counter++;
}
}



cout << "\nThere are " << counter - 1<< " primes less than " << n;

return 0;
}

How to calculate and display the result, the number of times executed loop?

Initialize a variable outside the while (continueGuessing) loop.

Inside the loop, increment that variable.

This will count how many guesses the person had.



Related Topics



Leave a reply



Submit