获取 Python 2.7 中代码块的执行时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15707056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:44:22  来源:igfitidea点击:

Get time of execution of a block of code in Python 2.7

pythonpython-2.7profiler

提问by lucacerone

I would like to measure the time elapsed to evaluate a block of code in a Python program, possibly separating between user cpu time, system cpu time and elapsed time.

我想测量评估 Python 程序中的代码块所用的时间,可能将用户 cpu 时间、系统 cpu 时间和经过时间分开。

I know the timeitmodule, but I have many self-written functions and it is not very easy to pass them in the setup process.

我知道这个timeit模块,但是我有很多自写的函数,在设置过程中传递它们不是很容易。

I would rather have something that could be used like:

我宁愿有一些可以使用的东西:

#up to here I have done something....
start_counting() #or whatever command used to mark that I want to measure
                   #the time elapsed in the next rows
# code I want to evaluate
user,system,elapsed = stop_counting() #or whatever command says:
                                      #stop the timer and return the times

The user and system CPU times are not essential (though I would like to measure them), but for the elapsed time I would like to be able to do something like this, rather than using complicated commands or modules.

用户和系统 CPU 时间不是必需的(尽管我想测量它们),但是对于经过的时间,我希望能够做这样的事情,而不是使用复杂的命令或模块。

采纳答案by Andrew Clark

To get the elapsed time in seconds, you can use timeit.default_timer():

要以秒为单位获取经过的时间,您可以使用timeit.default_timer()

import timeit
start_time = timeit.default_timer()
# code you want to evaluate
elapsed = timeit.default_timer() - start_time

timeit.default_timer()is used instead of time.time()or time.clock()because it will choose the timing function that has the higher resolution for any platform.

timeit.default_timer()用于代替time.time()time.clock()因为它将为任何平台选择具有更高分辨率的计时函数。

回答by Yarkee

I always use a decorator to do some extra work for a existing function, including to get the execution time. It is pythonic and simple.

我总是使用装饰器为现有函数做一些额外的工作,包括获取执行时间。它是pythonic和简单的。

import time

def time_usage(func):
    def wrapper(*args, **kwargs):
        beg_ts = time.time()
        retval = func(*args, **kwargs)
        end_ts = time.time()
        print("elapsed time: %f" % (end_ts - beg_ts))
        return retval
    return wrapper

@time_usage
def test():
    for i in xrange(0, 10000):
        pass

if __name__ == "__main__":
    test()

回答by monklof

You can achieve this through the Context Manager, for example:

您可以通过上下文管理器实现这一点,例如:

from contextlib import contextmanager
import time
import logging
@contextmanager
def _log_time_usage(prefix=""):
    '''log the time usage in a code block
    prefix: the prefix text to show
    '''
    start = time.time()
    try:
        yield
    finally:
        end = time.time()
        elapsed_seconds = float("%.2f" % (end - start))
        logging.debug('%s: elapsed seconds: %s', prefix, elapsed_seconds)

use example:

使用示例:

with _log_time_usage("sleep 1: "):
    time.sleep(1)

回答by Michael Herrmann

I found myself solving this problem again and again, so I finally created a libraryfor it. Install with pip install timer_cm. Then:

我发现自己一次又一次地解决了这个问题,所以我终于为它创建了一个。安装pip install timer_cm. 然后:

from time import sleep
from timer_cm import Timer

with Timer('Long task') as timer:
    with timer.child('First step'):
        sleep(1)
    for _ in range(5):
        with timer.child('Baby steps'):
            sleep(.5)

Output:

输出:

Long task: 3.520s
  Baby steps: 2.518s (71%)
  First step: 1.001s (28%)

回答by valex

There is one more option which i loves a lot now for simplicity - ipython. In ipython you got a lot of useful stuff plus:

为了简单起见,我现在非常喜欢另一种选择 - ipython。在 ipython 中,你得到了很多有用的东西,另外:

%time <expression>- to get straight cpu and wall time on expression

%time <expression>- 在表达上获得直接的 CPU 和墙上时间

%timeit <expression>- to get cpu and wall time in a loop of expression

%timeit <expression>- 在表达式循环中获取 CPU 和挂机时间

回答by Christopher Peisert

Python 3 - Simple solution using standard library

Python 3 - 使用标准库的简单解决方案

Option 1: Triple quote the code

选项 1:三重引用代码

import inspect
import timeit


code_block = inspect.cleandoc("""
    base = 123456789
    exponent = 100
    return base ** exponent
    """)
print(f'\Code block: {timeit.timeit(code_block, number=1)} elapsed seconds')

inspect.cleandochandles the removal of extra tabs and whitespace so that blocks of code can be copied and pasted without getting indentation errors.

inspect.cleandoc处理多余的制表符和空格的删除,以便可以复制和粘贴代码块而不会出现缩进错误。

 

 

Option 2: Place code block in a function

选项 2:将代码块放在函数中

import timeit


def my_function():
    base = 123456789
    exponent = 100
    return base ** exponent


if __name__ == '__main__':
    print(f'With lambda wrapper: {timeit.timeit(lambda: my_function(), number=1)} elapsed seconds')

Note that a function call will add additional execution time versus timing the function body directly.

请注意,与直接为函数体计时相比,函数调用会增加额外的执行时间。