我想测量执行一个函数所花费的时间。我没时间工作:
import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
我想测量执行一个函数所花费的时间。我没时间工作:
import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
当前回答
使用timeit.default_timer而不是timeit.timeit。前者自动提供您的平台和Python版本上可用的最佳时钟:
from timeit import default_timer as timer
start = timer()
# ...
end = timer()
print(end - start) # Time in seconds, e.g. 5.38091952400282
timeit.default_timer被分配给time.time()或time.clock(),具体取决于操作系统。在Python 3.3+default_timer上,所有平台上都有time.perf_counter()。请参见Python-time.cclock()与time.time()-精度?
另请参见:
正在优化代码如何优化速度
其他回答
使用探查器模块。它提供了非常详细的概况。
import profile
profile.run('main()')
它输出类似于:
5 function calls in 0.047 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(exec)
1 0.047 0.047 0.047 0.047 :0(setprofile)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
0 0.000 0.000 profile:0(profiler)
1 0.000 0.000 0.047 0.047 profile:0(main())
1 0.000 0.000 0.000 0.000 two_sum.py:2(twoSum)
我发现它很有启发性。
使用time.time来测量执行情况,可以获得命令的总体执行时间,包括计算机上其他进程花费的运行时间。这是用户注意到的时候,但如果你想比较不同的代码片段/算法/函数/。。。
有关timeit的更多信息:
使用timeit模块timeit–对少量Python代码的执行进行计时
如果您想深入了解剖析:
http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Profiling_Code如何评测python脚本?
更新:我使用http://pythonhosted.org/line_profiler/在过去的一年中,我们做了很多工作,发现它非常有用,建议使用它来代替Pythons配置文件模块。
时间也可以通过%timeit魔法函数测量,如下所示:
%timeit -t -n 1 print("hello")
n 1仅用于运行功能1次。
如果您想方便地对函数计时,可以使用一个简单的修饰符:
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
original_return_val = func(*args, **kwargs)
end = time.perf_counter()
print("time elapsed in ", func.__name__, ": ", end - start, sep='')
return original_return_val
return wrapper
您可以在您希望计时的函数上使用它,如下所示:
@timing_decorator
def function_to_time():
time.sleep(1)
function_to_time()
无论何时调用function_to_time,它都会打印所用的时间和正在计时的函数的名称。
除了ipython中的%timeit之外,您还可以使用%%timeit进行多行代码片段:
In [1]: %%timeit
...: complex_func()
...: 2 + 2 == 5
...:
...:
1 s ± 1.93 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
同样,它也可以以同样的方式在jupyter笔记本中使用,只需将magic%%timeit放在单元格的开头。