【问题标题】:How can I use the cProfile module to time each funtion in python?如何使用 cProfile 模块对 python 中的每个函数进行计时?
【发布时间】:2015-12-01 23:17:45
【问题描述】:

我有一个 Python 程序,它接受多个命令行参数并在多个函数中使用它们。如何使用 cProfile(在我的代码中)获取每个函数的运行时间? (我仍然希望程序完成后正常运行)。但是我无法弄清楚如何,例如我无法使用

cProfile.run('loadBMPImage(sys.argv[1])')

测试函数loadBMPImage的运行时间。我不能使用sys.argv[1] 作为参数。如果每个函数都依赖于命令行参数,我知道如何使用 cProfile 测试每个函数的运行时间并打印到标准输出吗?此外,cProfile 必须集成到代码本身中。谢谢

【问题讨论】:

    标签: python profiler cprofile


    【解决方案1】:

    我运行

    python program with -m cProfile

    示例:

    python -m cProfile <myprogram.py>

    这将需要对 myprogram.py 进行零更改

    【讨论】:

      【解决方案2】:

      有几种方法。

      import cProfile
      import pstats
      
      import sys
      
      
      def function(n):
          a = 1
          for i in range(n):
              a += 1
          return a
      

      第一个是使用简单的包装器runctx(),它允许您为执行的字符串指定全局变量和局部变量。在下面的示例中,我使用globals() 传递function 对象,并使用locals 传递参数,但当然可以不同的排列方式。

      def profile1():
          cProfile.runctx("function(n)", globals(), dict(n=int(sys.argv[1])), filename='test')
          return pstats.Stats('test')
      

      无需与exec 混淆的更好方法是使用Profile 类。这样你就可以分析一段常规代码:

      def profile2():
          pr = cProfile.Profile()
          pr.enable()
          function(int(sys.argv[1]))
          pr.disable()
          return pstats.Stats(pr)
      

      为了完整起见,使示例可运行

      if __name__ == '__main__':
          profile1().print_stats()
          profile2().print_stats()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-18
        • 2017-04-19
        • 2015-10-06
        • 1970-01-01
        • 2014-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多