如何获取每次迭代的时间执行?Python

2024-07-04 08:07:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

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

我在文档时间模块中找到,但不知道如何使用


Tags: in密码fornpzerosrangemingrid
2条回答

使用此模块的一个简单方法是让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

希望这有帮助!

一个简单的解决方案是

start = time.time()
... do the computation ...
stop = time.time()
duration = stop - start

相关问题 更多 >

    热门问题