【问题标题】:How do I get the time execution for each iteration? Python [duplicate]如何获得每次迭代的时间执行? Python [重复]
【发布时间】:2013-11-30 14:33:23
【问题描述】:

我有这个代码:

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

我在文档时间模块中找到但我不明白如何使用

【问题讨论】:

标签: python


【解决方案1】:

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

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    一个简单的解决方案是

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-15
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      相关资源
      最近更新 更多