2
    from itertools import permutations
    import random
    import pprint
    import timeit

    start_time = timeit.default_timer()
    count = 0
    def gird(board_size):

        print ("\n".join('# ' * inrange + 'Q ' + '# ' * (8-inrange-1)\

    for inrange in board_size) + "\n\n= = new board  \n")
    count+=1
    coloms  = range(8)
    for board_size in permutations(coloms):
        if 8 == len(set(board_size[inrange]+inrange for inrange in coloms)):
            if 8 == len(set(board_size[inrange]-inrange for inrange in coloms)):
                gird(board_size)


                elapsed = timeit.default_timer() - start_time
                print(elapsed)
                print(count)

I want to see how many times this code has run. I have to measure the search cost (number of iterations until it hits a minimum) and percentage of solved problems. This is an 8 queen problem.

nmichaels
  • 49,466
  • 12
  • 107
  • 135
odisho eivazi
  • 65
  • 1
  • 1
  • 8

1 Answers1

6

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".

James Mills
  • 18,669
  • 3
  • 49
  • 62
  • So only way I can keep track of number of times a file has been run is not possible without writing to a file I guess? There can't be a like a permanent variable in the script that can keep track of this? – user3326078 Jul 27 '18 at 19:26
  • Writing a variable out to your source files is no different to writing to some other arbitrary file on disk. The hard part is that you have to parse your source file and correctly write a new version or you'll end up with `SyntaxError`(s) on your next run. – James Mills Jul 29 '18 at 06:13