【问题标题】:How to use timeit when timing a function计时函数时如何使用timeit
【发布时间】:2013-10-01 09:24:12
【问题描述】:

首先让我说我对 python 几乎一无所知,但必须用三种不同的语言编写程序(已经用 java 和 c++ 完成)。

我需要能够为某个方法的执行计时一定次数,然后打印整个执行时间所花费的时间。

我有函数A(即performSearch(arrayTest),其中arrayTest 是一个已知大小的数组)。 A 被执行 10 次

我需要能够计算从执行A 之前到执行A 之后所花费的时间。

【问题讨论】:

  • 您已经完美地描述了您的情况。你有什么问题?

标签: python timeit


【解决方案1】:

您可以阅读如何使用 timeit here

假设您在同一个文件中有一个名为 performSearch 的函数,您的运行 timeit 从以下将起作用。

import timeit

def performSearch(array):
    array.sort()


arrayTest = ["X"]*1000

if __name__ == "__main__":
    print timeit.timeit("performSearch(arrayTest)","from __main__ import performSearch, arrayTest",number=10)

返回:

0.000162031766607

【讨论】:

  • 我收到语法错误。这是完整的代码+你说要使用pastebin.com/71uXny9L
  • 执行搜索是您的功能而不是功能A
  • from __main__ import functionA, arrayTest 更改为 from __main__ import performSearch, arrayTest
  • 当我说functionA时,我是通用的,希望不需要我的整个代码
  • 我可以理解,您需要做的就是将我的那些说 functionA 的位更改为 performSearch。
【解决方案2】:

你可以这样做:

import time

start = time.time()
A()
end = time.time()
print "Took %f ms" % ((end - start) * 1000.0)

【讨论】:

  • 这是一种更干净、更好的方法,同时实现了几乎相同的结果(至少在我的情况下)。
  • timeit 使用更精确的计数器,具有进行多次测量的功能,并默认关闭垃圾收集
【解决方案3】:

如果你想要更简单的东西

import time
startMillis = int(round(time.time() * 1000))
print startMillis
time.sleep(5) # this is your function that takes time to execute
endMillis = int(round(time.time() * 1000))
print endMillis

timeTaken = endMillis - startMillis

【讨论】:

    【解决方案4】:

    您可以使用以下代码作为示例:

    import timeit
    
    def string_generator(size):
        return (size/8) * "ABCDEFGH"
    
    if __name__ == "__main__":
        #the below line runs the statement inside of '' for 100 times (number).
        print timeit.timeit('"-".join(str(n) for n in range(100))',number=100)
        #the below line runs the statement inside of '' for 10 times (number) and repeat it 3 times.
        print timeit.repeat('"-".join(str(n) for n in range(100))',repeat=3,number=10)
        #if you would like to time a function, you can do it similar to below example:
        print timeit.timeit("string_generator(2**12)", setup="from __main__ import string_generator")
    

    结果是:

    0.00784516334534
    [0.0009770393371582031, 0.00036597251892089844, 0.00037407875061035156]
    0.414484977722
    

    结果的单位是秒。 python网站中存在更多示例。 enter link description here

    你也可以使用 ipython。下面列出了相同的示例。

    In [25]: %timeit "-".join(str(n) for n in range(100))
    

    结果是:

    10000 loops, best of 3: 22.9 µs per loop
    

    如你所见,单位是宏秒。

    【讨论】:

      【解决方案5】:

      是的,只是时间。

      total= 0
      for i in range(1000):
          start= time.clock()
          function()
          end= time.clock()
          total += end-start
      time= total/1000
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-20
        • 2023-03-04
        • 2010-12-10
        • 2014-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多