我有这段代码:
for times in range(50):
factor = (min(getHeight(),getWidth()) / math.sqrt(qtdPosicoes)) * guess()
positionInGrid = {}
grid = np.zeros((getGridColumns(),getGridLines()))
groupMatrix = np.zeros((grid.shape[0], grid.shape[1]))
groups = getGroups(grid, listaComPosicoes, getXRanges(listaComPosicoes),getYRanges(listaComPosicoes))
solution = calculaSilhueta()
if bestSolution is None or solution > bestSolution:
bestSolution = solution
我在文档时间模块中找到了但我不明白如何使用
答案 0 :(得分:5)
使用此模块的一种简单方法是让time.time()
标记代码的开头,然后再次使用time.time()
标记代码的结尾。之后,减去它们,以便获得持续时间。
所以你的代码应该是:
for times in range(50):
start = time.time()
#do some stuff
stop = time.time()
duration = stop-start
print(duration)
示例:
>>> for i in range(3):
start = time.time()
print(i)
stop = time.time()
print(stop-start)
0
0.08444404602050781
1
0.014003992080688477
2
0.009001970291137695
但更好的选择是使用timeit
模块,这更容易:
>>> import timeit
>>> def myfunction(time):
print(time)
>>> result = timeit.timeit("for i in range(2): myfunction(i)", setup="from __main__ import myfunction", number=1)
0
1
>>> result
0.0868431608504352
希望这有帮助!
答案 1 :(得分:3)
一个简单的解决方案是
start = time.time()
... do the computation ...
stop = time.time()
duration = stop - start