时序代码块 - Python

tul*_*ans 0 python benchmarking timing

我正在尝试测量在Python中运行一组指令所需的时间,但我不想写下这样的内容:

start = time.clock()
...
<lines of code>
...
time_elapsed = time.clock() - start
Run Code Online (Sandbox Code Playgroud)

相反,我想知道是否有一种方法可以将指令块作为参数发送给返回已用时间的函数,如

time_elapsed = time_it_takes(<lines of code>)
Run Code Online (Sandbox Code Playgroud)

这种方法的实现可能是这样的

def time_it_takes(<lines of code>):
  start = time.clock()
  result = <lines of code>
  return (result, time.clock() - start)
Run Code Online (Sandbox Code Playgroud)

有人知道我能否做到这一点?提前致谢.

dan*_*dee 6

这将很好地利用装饰器.你可以写一个像这样做的装饰器

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)

        print('The function ran for', time.time() - start)
    return wrapper


@timer
def just_sleep():
    time.sleep(5)

just_sleep()
Run Code Online (Sandbox Code Playgroud)

产量

The function ran for 5.0050904750823975
Run Code Online (Sandbox Code Playgroud)

然后你可以装饰你想要的任何功能@timer,你也可以在装饰器内做一些其他奇特的事情.就像函数运行超过15秒做一些事情......否则做另一件事

注意:这不是测量python中函数执行时间的最准确方法


tde*_*ney 5

您可以构建自己的上下文管理器来计时相对较长的代码。

import time

class MyTimer(object):

    def __enter__(self):
        self.start = time.clock()
        return self

    def __exit__(self, typ, value, traceback):
        self.duration = time.clock() - self.start

with MyTimer() as timer:
    time.sleep(3)
print(timer.duration)
Run Code Online (Sandbox Code Playgroud)

但是要小心你测量的东西。在 Linux 上time.clock是 cpu 运行时,但在 Windows 上(cpu 运行时不容易获得)是挂钟。