我想测量执行一个函数所花费的时间。我没时间工作:
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)
当前回答
除了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放在单元格的开头。
其他回答
你可以使用timeit。
下面是一个示例,说明如何使用Python REPL测试naive_func,该函数接受参数:
>>> import timeit
>>> def naive_func(x):
... a = 0
... for i in range(a):
... a += i
... return a
>>> def wrapper(func, *args, **kwargs):
... def wrapper():
... return func(*args, **kwargs)
... return wrapper
>>> wrapped = wrapper(naive_func, 1_000)
>>> timeit.timeit(wrapped, number=1_000_000)
0.4458435332577161
若函数并没有任何参数,那个么就不需要包装函数。
如果您想方便地对函数计时,可以使用一个简单的修饰符:
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,它都会打印所用的时间和正在计时的函数的名称。
这里有一个很好的文档记录和完全类型提示的装饰器,我将其用作通用工具:
from functools import wraps
from time import perf_counter
from typing import Any, Callable, Optional, TypeVar, cast
F = TypeVar("F", bound=Callable[..., Any])
def timer(prefix: Optional[str] = None, precision: int = 6) -> Callable[[F], F]:
"""Use as a decorator to time the execution of any function.
Args:
prefix: String to print before the time taken.
Default is the name of the function.
precision: How many decimals to include in the seconds value.
Examples:
>>> @timer()
... def foo(x):
... return x
>>> foo(123)
foo: 0.000...s
123
>>> @timer("Time taken: ", 2)
... def foo(x):
... return x
>>> foo(123)
Time taken: 0.00s
123
"""
def decorator(func: F) -> F:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
nonlocal prefix
prefix = prefix if prefix is not None else f"{func.__name__}: "
start = perf_counter()
result = func(*args, **kwargs)
end = perf_counter()
print(f"{prefix}{end - start:.{precision}f}s")
return result
return cast(F, wrapper)
return decorator
示例用法:
from timer import timer
@timer(precision=9)
def takes_long(x: int) -> bool:
return x in (i for i in range(x + 1))
result = takes_long(10**8)
print(result)
输出:耗时:4.942629056秒真的
可以通过以下方式检查doctest:
$ python3 -m doctest --verbose -o=ELLIPSIS timer.py
类型提示:
$ mypy timer.py
基于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
给定要计时的函数,
测试.py:
def foo():
# print "hello"
return "hello"
使用timeit的最简单方法是从命令行调用它:
% python -mtimeit -s'import test' 'test.foo()'
1000000 loops, best of 3: 0.254 usec per loop
不要尝试使用time.time或time.clock(天真地)来比较函数的速度。他们会给出误导性的结果。
PS.不要将打印语句放在您希望计时的函数中;否则测量的时间将取决于终端的速度。