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)
我想知道这段代码运行了多少次,我必须测量搜索成本(迭代次数达到最小值)和已解决问题的百分比。这是一个8皇后问题。
答案 0 :(得分:3)
我如何计算在python中执行了多少次程序
我能想到的唯一的方式来解决你的问题,因为你已经描述了它,而不是运行你的功能N次是这样的:
示例:强>
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()
样本运行:
$ 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
但是我必须指出,这不是一个非常好的方法来衡量"程序的性能或您编写的功能。您应该查看hotshot或timeit之类的内容,或者在内部多次运行您的功能并测量"正确的事情"。