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

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

当前回答

这是一种很晚的反应,但也许对某人来说是有目的的。这是一种我认为非常干净的方法。

import time

def timed(fun, *args):
    s = time.time()
    r = fun(*args)
    print('{} execution took {} seconds.'.format(fun.__name__, time.time()-s))
    return(r)

timed(print, "Hello")

请记住,“print”是Python 3中的函数,而不是Python 2.7中的函数。但是,它可以与任何其他功能一起使用。干杯

其他回答

使用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.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

计算操作持续时间的最简单方法:

import time

start_time = time.monotonic()

<operations, programs>

print('seconds: ', time.monotonic() - start_time)

这里有官方文件。

还有一种使用timeit的方法:

from timeit import timeit

def func():
    return 1 + 1

time = timeit(func, number=1)
print(time)

这是另一种方法:

>> from pytictoc import TicToc
>> t = TicToc() # create TicToc instance
>> t.tic() # Start timer
>> # do something
>> t.toc() # Print elapsed time
Elapsed time is 2.612231 seconds.

与传统方式相比:

>> from time import time
>> t1 = time()
>> # do something
>> t2 = time()
>> elapsed = t2 - t1
>> print('Elapsed time is %f seconds.' % elapsed)
Elapsed time is 2.612231 seconds.

安装:

pip install pytictoc

有关详细信息,请参阅PyPi页面。