我想测量执行一个函数所花费的时间。我没时间工作:

import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)

当前回答

您可以使用Benchmark Timer(免责声明:我是作者):

基准计时器使用BenchmarkTimer类来测量执行某段代码所需的时间。这比内置的timeit函数具有更大的灵活性,并且与其他代码在相同的范围内运行。安装pip安装git+https://github.com/michaelitvin/benchmark-timer.git@main#egg=基准计时器用法单次迭代示例从benchmark_timer导入BenchmarkTimer导入时间使用BenchmarkTimer(name=“MySimpleCode”)作为tm,tm.single_ieration():睡眠时间(.3)输出:正在对标MySimpleCode。。。MySimpleCode基准:n_iters=1 avg=0.300881s std=0.000000s range=[0.3000881s ~ 0.300881s]多次迭代示例从benchmark_timer导入BenchmarkTimer导入时间使用BenchmarkTimer(name=“MyTimedCode”,print_iters=True)作为tm:对于tm迭代中的timing_iteration(n=5,预热=2):定时重复:睡眠时间(.1)打印(“\n===============\n”)print(“定时列表:”,列表(tm.timenings.values()))输出:正在对标MyTimedCode。。。[MyTimedCode]iter=0耗时0.099755s(预热)[MyTimedCode]iter=1耗时0.100476秒(预热)[MyTimedCode]iter=2耗时0.100189秒[MyTimedCode]iter=3耗时0.099900s[MyTimedCode]iter=4耗时0.100888秒MyTimedCode基准:n_iters=3 avg=0.100326s std=0.000414s range=[0.099900s ~ 0.100888s]===================时间列表:[0.1001885000000001,0.09990049999999995,0.10088760000000008]

其他回答

使用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(),根据您的要求,要有明确的行为。

除了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放在单元格的开头。

基于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

以下是一个答案,使用:

对代码片段进行计时的简洁上下文管理器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

虽然问题中没有严格要求,但通常情况下,您需要一种简单、统一的方法来递增地测量几行代码之间的经过时间。

如果您使用的是Python 3.8或更高版本,则可以使用赋值表达式(也称为walrus运算符)以相当优雅的方式实现这一点:

import time

start, times = time.perf_counter(), {}

print("hello")
times["print"] = -start + (start := time.perf_counter())

time.sleep(1.42)
times["sleep"] = -start + (start := time.perf_counter())

a = [n**2 for n in range(10000)]
times["pow"] = -start + (start := time.perf_counter())

print(times)

=>

{'print': 2.193450927734375e-05, 'sleep': 1.4210970401763916, 'power': 0.005671024322509766}