我正在 Windows 上用 python 编程,希望准确测量函数运行所需的时间。我编写了一个函数“time_it”,它接受另一个函数,运行它,并返回运行所花费的时间。
def time_it(f, *args):
start = time.clock()
f(*args)
return (time.clock() - start)*1000
我调用了 1000 次并对结果进行平均。 (最后的 1000 常数是以毫秒为单位给出答案。)
这个函数似乎可以工作,但我有一种挥之不去的感觉,我做错了什么,而且通过这种方式,我使用的时间比函数运行时实际使用的时间还要多。
是否有更标准或可接受的方法来做到这一点?
当我将测试函数更改为调用打印以使其需要更长的时间时,我的 time_it 函数返回平均 2.5 毫秒,而 cProfile.run('f()') 返回平均 7.0 毫秒。我认为我的函数会高估时间(如果有的话),这里发生了什么?
另请注意,我关心的是函数之间的相对时间,而不是绝对时间,因为这显然会根据硬件和其他因素而变化。
Use the timeit module http://docs.python.org/library/timeit.html来自Python标准库。
基本用法:
from timeit import Timer
# first argument is the code to be run, the second "setup" argument is only run once,
# and it not included in the execution time.
t = Timer("""x.index(123)""", setup="""x = range(1000)""")
print t.timeit() # prints float, for example 5.8254
# ..or..
print t.timeit(1000) # repeat 1000 times instead of the default 1million
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)