我想测量执行一个函数所花费的时间。我没时间工作:
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)
当前回答
基于https://stackoverflow.com/a/30024601/5095636,以下为无lambda版本,如flake8根据E731对lambda使用的警告:
from contextlib import contextmanager
from timeit import default_timer
@contextmanager
def elapsed_timer():
start_time = default_timer()
class _Timer():
start = start_time
end = default_timer()
duration = end - start
yield _Timer
end_time = default_timer()
_Timer.end = end_time
_Timer.duration = end_time - start_time
测试:
from time import sleep
with elapsed_timer() as t:
print("start:", t.start)
sleep(1)
print("end:", t.end)
t.start
t.end
t.duration
其他回答
使用探查器模块。它提供了非常详细的概况。
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)
我发现它很有启发性。
还有一种使用timeit的方法:
from timeit import timeit
def func():
return 1 + 1
time = timeit(func, number=1)
print(time)
以下是一个答案,使用:
对代码片段进行计时的简洁上下文管理器time.perf_counter()计算时间增量。与time.time()相反,它是不可调整的(sysadmin和守护程序都不能更改其值),因此应该首选它(参见文档)python3.10+(因为键入,但可以很容易地适应以前的版本)
import time
from contextlib import contextmanager
from typing import Iterator
@contextmanager
def time_it() -> Iterator[None]:
tic: float = time.perf_counter()
try:
yield
finally:
toc: float = time.perf_counter()
print(f"Computation time = {1000*(toc - tic):.3f}ms")
如何使用它的示例:
# Example: vector dot product computation
with time_it():
A = B = range(1000000)
dot = sum(a*b for a,b in zip(A,B))
# Computation time = 95.353ms
附录
import time
# to check adjustability
assert time.get_clock_info('time').adjustable
assert time.get_clock_info('perf_counter').adjustable is False
使用time.time()测量两点之间经过的墙上时钟时间:
import time
start = time.time()
print("hello")
end = time.time()
print(end - start)
这给出了以秒为单位的执行时间。
Python 3.3之后的另一个选项可能是使用perf_counter或process_time,具体取决于您的需求。在3.3之前,建议使用time.clock(感谢Amber)。但是,它目前已被弃用:
在Unix上,将当前处理器时间作为浮点数返回以秒表示。准确度,事实上就是定义“处理器时间”的含义取决于C函数的含义具有相同名称。在Windows上,此函数返回自该函数的第一次调用,作为浮点数,基于Win32函数QueryPerformanceCounter()。分辨率通常为优于一微秒。自3.3版起已弃用:此函数的行为取决于在平台上:改用perf_counter()或process_time(),根据您的要求,要有明确的行为。
使用time.time来测量执行情况,可以获得命令的总体执行时间,包括计算机上其他进程花费的运行时间。这是用户注意到的时候,但如果你想比较不同的代码片段/算法/函数/。。。
有关timeit的更多信息:
使用timeit模块timeit–对少量Python代码的执行进行计时
如果您想深入了解剖析:
http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Profiling_Code如何评测python脚本?
更新:我使用http://pythonhosted.org/line_profiler/在过去的一年中,我们做了很多工作,发现它非常有用,建议使用它来代替Pythons配置文件模块。