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

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

当前回答

我更喜欢这个。timeit医生太令人困惑了。

from datetime import datetime 

start_time = datetime.now() 

# INSERT YOUR CODE 

time_elapsed = datetime.now() - start_time 

print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))

注意,这里没有进行任何格式化,我只是在打印输出中写入hh:mm:ss,以便可以解释time_elapsed

其他回答

对于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')

时间也可以通过%timeit魔法函数测量,如下所示:

%timeit -t -n 1 print("hello")

n 1仅用于运行功能1次。

这里有一个很好的文档记录和完全类型提示的装饰器,我将其用作通用工具:

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

使用time.time来测量执行情况,可以获得命令的总体执行时间,包括计算机上其他进程花费的运行时间。这是用户注意到的时候,但如果你想比较不同的代码片段/算法/函数/。。。

有关timeit的更多信息:

使用timeit模块timeit–对少量Python代码的执行进行计时

如果您想深入了解剖析:

http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Profiling_Code如何评测python脚本?

更新:我使用http://pythonhosted.org/line_profiler/在过去的一年中,我们做了很多工作,发现它非常有用,建议使用它来代替Pythons配置文件模块。

以下是我在阅读了许多好答案以及其他几篇文章之后的发现。

首先,如果你在timeit和time.time之间进行辩论,timeit有两个优点:

timeit选择操作系统和Python版本上可用的最佳计时器。然而,timeit禁用垃圾收集,这不是您可能想要或不想要的。

现在的问题是,时间并不是那么简单,因为它需要设置,当你有大量的导入时,事情会变得很糟糕。理想情况下,您只需要一个装饰器或使用块和度量时间。不幸的是,没有内置功能可用于此,因此您有两个选项:

选项1:使用时间预算库

timebudget是一个多功能且非常简单的库,您可以在pip安装后仅在一行代码中使用它。

@timebudget  # Record how long this function takes
def my_method():
    # my code

选项2:使用我的小模块

我创建了一个名为timing.py的计时实用程序模块。只需将这个文件放到项目中并开始使用它。唯一的外部依赖是runstats,它同样很小。

现在,只需在函数前面放置一个装饰器,就可以对任何函数计时:

import timing

@timing.MeasureTime
def MyBigFunc():
    #do something time consuming
    for i in range(10000):
        print(i)

timing.print_all_timings()

如果您想对代码的一部分计时,只需将其放入块中:

import timing

#somewhere in my code

with timing.MeasureBlockTime("MyBlock"):
    #do something time consuming
    for i in range(10000):
        print(i)

# rest of my code

timing.print_all_timings()

优势:

有几个半备份版本,所以我想指出几个亮点:

出于前面描述的原因,请使用timeit中的计时器,而不是time.time。如果需要,可以在计时期间禁用GC。Decorator接受带有命名或未命名参数的函数。能够在块计时中禁用打印(与timing.MeasureBlockTime()一起使用为t,然后为t.passed)。能够为块计时启用gc。