我想测量执行一个函数所花费的时间。我没时间工作:
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)
当前回答
下面是一个返回“hh:mm:ss”字符串的小型计时器类:
class Timer:
def __init__(self):
self.start = time.time()
def restart(self):
self.start = time.time()
def get_time_hhmmss(self):
end = time.time()
m, s = divmod(end - self.start, 60)
h, m = divmod(m, 60)
time_str = "%02d:%02d:%02d" % (h, m, s)
return time_str
用法:
# Start timer
my_timer = Timer()
# ... do something
# Get time string:
time_hhmmss = my_timer.get_time_hhmmss()
print("Time elapsed: %s" % time_hhmmss )
# ... use the timer again
my_timer.restart()
# ... do something
# Get time:
time_hhmmss = my_timer.get_time_hhmmss()
# ... etc
其他回答
我喜欢简单(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
使用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()-精度?
另请参见:
正在优化代码如何优化速度
我参加聚会已经很晚了,但这种方法以前没有涉及过。当我们想要手动对某段代码进行基准测试时,我们可能需要首先找出哪些类方法占用了执行时间,这有时并不明显。我构建了以下元类来解决这个问题:
from __future__ import annotations
from functools import wraps
from time import time
from typing import Any, Callable, TypeVar, cast
F = TypeVar('F', bound=Callable[..., Any])
def timed_method(func: F, prefix: str | None = None) -> F:
prefix = (prefix + ' ') if prefix else ''
@wraps(func)
def inner(*args, **kwargs): # type: ignore
start = time()
try:
ret = func(*args, **kwargs)
except BaseException:
print(f'[ERROR] {prefix}{func.__qualname__}: {time() - start}')
raise
print(f'{prefix}{func.__qualname__}: {time() - start}')
return ret
return cast(F, inner)
class TimedClass(type):
def __new__(
cls: type[TimedClass],
name: str,
bases: tuple[type[type], ...],
attrs: dict[str, Any],
**kwargs: Any,
) -> TimedClass:
for name, attr in attrs.items():
if isinstance(attr, (classmethod, staticmethod)):
attrs[name] = type(attr)(timed_method(attr.__func__))
elif isinstance(attr, property):
attrs[name] = property(
timed_method(attr.fget, 'get') if attr.fget is not None else None,
timed_method(attr.fset, 'set') if attr.fset is not None else None,
timed_method(attr.fdel, 'del') if attr.fdel is not None else None,
)
elif callable(attr):
attrs[name] = timed_method(attr)
return super().__new__(cls, name, bases, attrs)
它允许如下使用:
class MyClass(metaclass=TimedClass):
def foo(self):
print('foo')
@classmethod
def bar(cls):
print('bar')
@staticmethod
def baz():
print('baz')
@property
def prop(self):
print('prop')
@prop.setter
def prop(self, v):
print('fset')
@prop.deleter
def prop(self):
print('fdel')
c = MyClass()
c.foo()
c.bar()
c.baz()
c.prop
c.prop = 2
del c.prop
MyClass.bar()
MyClass.baz()
它打印:
foo
MyClass.foo: 1.621246337890625e-05
bar
MyClass.bar: 4.5299530029296875e-06
baz
MyClass.baz: 4.291534423828125e-06
prop
get MyClass.prop: 3.814697265625e-06
fset
set MyClass.prop: 3.5762786865234375e-06
fdel
del MyClass.prop: 3.5762786865234375e-06
bar
MyClass.bar: 3.814697265625e-06
baz
MyClass.baz: 4.0531158447265625e-06
它可以与其他答案相结合,以更精确的方式代替time.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
仅Python 3:
由于从Python 3.3开始,time.cclock()已被弃用,因此您将希望使用time.perf_counter()进行系统范围的计时,或使用time.process_time()进行进程范围的计时(就像您以前使用time.cclok()的方式一样):
import time
t = time.process_time()
#do some stuff
elapsed_time = time.process_time() - t
新函数process_time将不包括睡眠期间经过的时间。