【问题标题】:Timing blocks of code - Python [duplicate]代码的时序块 - Python [重复]
【发布时间】:2017-02-21 21:36:00
【问题描述】:

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

start = time.clock()
...
<lines of code>
...
time_elapsed = time.clock() - start

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

time_elapsed = time_it_takes(<lines of code>)

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

def time_it_takes(<lines of code>):
  start = time.clock()
  result = <lines of code>
  return (result, time.clock() - start)

有人知道我是否有办法做到这一点?提前致谢。

【问题讨论】:

    标签: python timing benchmarking


    【解决方案1】:

    这将是装饰器的一个很好的用途。你可以写一个这样的装饰器

    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()
    

    输出

    The function ran for 5.0050904750823975
    

    然后你可以用@timer 装饰任何你想要的函数,你也可以在装饰器中做一些其他的花哨的事情。就像如果函数运行超过 15 秒做某事...否则做另一件事

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

    【讨论】:

      【解决方案2】:

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

      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)
      

      但要小心您测量的内容。在 Linux 上time.clock 是 cpu 运行时间,但在 Windows(cpu 运行时间不容易获得)上它是一个挂钟。

      【讨论】:

        【解决方案3】:

        如果您使用 IPython,这是一件好事,您可以将代码构造为单行,即函数调用:

        %timeit your-code
        

        这对我来说很方便。希望对您有所帮助。

        【讨论】:

          【解决方案4】:

          使用python -m cProfile myscript.py它提供有关方法时间消耗的完整日志。

          【讨论】:

            猜你喜欢
            • 2015-07-19
            • 2019-08-03
            • 1970-01-01
            • 2022-07-07
            • 1970-01-01
            • 2015-05-04
            • 1970-01-01
            • 2016-10-30
            • 1970-01-01
            相关资源
            最近更新 更多