【问题标题】:How to measure the speed of a python function如何测量python函数的速度
【发布时间】:2017-11-24 10:43:18
【问题描述】:

我通常作为竞争对手在 www.codefights.com 上编写代码(函数)。所以速度是代码的重要部分之一。如何测量python语言中某个代码的速度,无论是lambda函数还是def函数。

【问题讨论】:

  • 你可以使用 datetiem
  • Python 为此提供了timeit 模块。
  • 告诉我们您的环境是什么。例如,您使用的是 IPython 还是 Spyder?有些环境有这种事情的捷径。
  • 使用timeit 模块。或者使用time 模块制作自定义时间装饰器。
  • 如果你的函数运行时间比较长,不想重复调用,就在调用前用start = time.process_time()(或time.time())获取当前时间,然后获取通话后再次显示当前时间,因此所用时间将是 time.process_time() - start 的差异。

标签: python performance performance-measuring


【解决方案1】:

当我需要测量一些非常具体的代码的执行时间时,我通常依赖以下方法:

https://docs.python.org/3/library/time.html

def howLong():
    startTime = time.time()
    time.sleep(3)
    print("Time to wake up, ~3 seconds have passed!")
    endTime = time.time()
    
    howMuchTime = endTime - startTime
    print(str(howMuchTime) + " sec")

if __name__ == '__main__':
    import time
    howLong()

结果

Time to wake up, ~3 seconds have passed!
3.013692855834961 sec

【讨论】:

    【解决方案2】:

    分 3 步 ;)

    第一步:安装line_profiler

    pip install line_profiler
    

    第 2 步:@profile 添加到您的代码中:

    from time import sleep
    
    @profile
    def so_slow(bar):
        sleep(5)
        return bar
    
    if __name__ == "__main__":
        so_slow(5)
    

    第 3 步:测试您的代码:

    kernprof -l -v your_code.py
    

    结果

    Wrote profile results to your_code.py.lprof
    Timer unit: 1e-06 s
    
    Total time: 5.00283 s
    File: your_code.py
    Function: so_slow at line 4
    
    Line #      Hits         Time  Per Hit   % Time  Line Contents
    ==============================================================
         4                                           @profile
         5                                           def so_slow(bar):
         6         1      5002830 5002830.0    100.0      sleep(5)
         7         1            2      2.0      0.0      return bar
    

    memory_profiler

    您也可以使用memory_profiler,安装它,添加配置文件并调用它:

    pip install memory_profiler
    python -m memory_profiler your_code.py
    


    结果:

    Filename: your_code.py
    
    Line #    Mem usage    Increment   Line Contents
    ================================================
         4   21.289 MiB    0.000 MiB   @profile
         5                             def so_slow(bar):
         6   21.289 MiB    0.000 MiB       sleep(5)
         7   21.289 MiB    0.000 MiB       return bar
    

    更新:

    您可以使用objgraph 查找memory leak 或绘制您的代码图:

    from time import sleep
    
    import objgraph
    x = [1]
    
    objgraph.show_backrefs([x], filename='sample-backref-graph.png')
    
    def so_slow(bar):
        sleep(5)
        return bar
    
    if __name__ == "__main__":
        so_slow(5)
    


    结果:

    参考:A guide to analyzing Python performance

    【讨论】:

    • 你知道是否可以删除“行内容”吗?我正在尝试阅读包含很多很多行文本的 PDF,并且我不希望这些文本混入我的控制台。我真的只需要整个脚本从头到尾的时间安排。
    【解决方案3】:

    您可以在 ipython 中使用它并使用 %time 来查看函数执行所需的分配时间:

    In [1]: def function(a,b):
       ...:     return a+b
       ...: 
    
    In [2]: %time function(1, 2)
    CPU times: user 5 µs, sys: 0 ns, total: 5 µs
    Wall time: 9.06 µs
    Out[2]: 3
    

    【讨论】:

      【解决方案4】:

      例如:

      import timeit
      
      def a():
          return 1+1
      
      print timeit.timeit(a, number=1000000)
      

      【讨论】:

        【解决方案5】:

        看看pythons标准libaray中的timeit模块:

        https://docs.python.org/2/library/timeit.html

        >>> import timeit
        >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
        0.8187260627746582
        >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
        0.7288308143615723
        >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
        0.5858950614929199
        

        要让 timeit 模块访问您定义的函数,您可以传递一个包含导入语句的设置参数:

        def test():
            """Stupid test function"""
            L = []
            for i in range(100):
                L.append(i)
        
        if __name__ == '__main__':
            import timeit
            print(timeit.timeit("test()", setup="from __main__ import test"))
        

        【讨论】:

          猜你喜欢
          • 2012-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-01
          • 2012-07-24
          • 2019-07-07
          • 2011-08-25
          相关资源
          最近更新 更多