我想测量执行一个函数所花费的时间。我没时间工作:
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)
当前回答
以下是一个答案,使用:
对代码片段进行计时的简洁上下文管理器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
其他回答
(仅使用Ipython)您可以使用%timeit来测量平均处理时间:
def foo():
print "hello"
然后:
%timeit foo()
结果如下:
10000 loops, best of 3: 27 µs per loop
我喜欢简单(python 3):
from timeit import timeit
timeit(lambda: print("hello"))
单个执行的输出为微秒:
2.430883963010274
说明:timeit默认执行匿名函数100万次,结果以秒为单位。因此,1次执行的结果相同,但平均以微秒为单位。
对于速度较慢的操作,添加较少的迭代次数,否则您可能会一直等待:
import time
timeit(lambda: time.sleep(1.5), number=1)
总迭代次数的输出始终以秒为单位:
1.5015795179999714
使用探查器模块。它提供了非常详细的概况。
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)
我发现它很有启发性。
对于Python 3
如果使用时间模块,则可以获取当前时间戳,然后执行代码,然后再次获取时间戳。现在,所用时间将是第一个时间戳减去第二个时间戳:
import time
first_stamp = int(round(time.time() * 1000))
# YOUR CODE GOES HERE
time.sleep(5)
second_stamp = int(round(time.time() * 1000))
# Calculate the time taken in milliseconds
time_taken = second_stamp - first_stamp
# To get time in seconds:
time_taken_seconds = round(time_taken / 1000)
print(f'{time_taken_seconds} seconds or {time_taken} milliseconds')
下面是另一个用于计时代码的上下文管理器-
用法:
from benchmark import benchmark
with benchmark("Test 1+1"):
1+1
=>
Test 1+1 : 1.41e-06 seconds
或者,如果您需要时间值
with benchmark("Test 1+1") as b:
1+1
print(b.time)
=>
Test 1+1 : 7.05e-07 seconds
7.05233786763e-07
基准.py:
from timeit import default_timer as timer
class benchmark(object):
def __init__(self, msg, fmt="%0.3g"):
self.msg = msg
self.fmt = fmt
def __enter__(self):
self.start = timer()
return self
def __exit__(self, *args):
t = timer() - self.start
print(("%s : " + self.fmt + " seconds") % (self.msg, t))
self.time = t
改编自http://dabeaz.blogspot.fr/2010/02/context-manager-for-timing-benchmarks.html