【问题标题】:Measuring program runtime in python在 python 中测量程序运行时
【发布时间】:2012-07-29 04:51:56
【问题描述】:

我有一个程序说:

for i in xrange(10):
    for p in xrange(10):
        print i, p

我希望能够以毫秒为单位打印程序在程序结束时执行的时间。

【问题讨论】:

    标签: python performance loops time


    【解决方案1】:

    使用python -m timeit -s 'import my_module' 'my_module.do_stuff()' 运行您的程序以查看运行时间信息。

    根据timeitdocumentation,只是滚动你自己有点棘手,所以它是为你提供的。

    【讨论】:

      【解决方案2】:

      尽管我更喜欢 @Julian 的方法,但您可以在 Python 代码中执行此操作,但仅提供此方法作为替代方法:

      from timeit import timeit
      
      def foo():
          for i in xrange(10):
              for p in xrange(10):
                  print i, p
      
      print timeit(setup='from __main__ import foo', stmt='foo()') # returns float of seconds taken to run
      

      【讨论】:

        【解决方案3】:

        我编写了一个小 sn-p,可以让您使用上下文管理器测量经过的时间。看看https://github.com/BaltoRouberol/timer-context-manager

        例子:

        from timer import Timer
        
        with Timer() as t:
            # Some code we want to time
        
        print t.elapsed_ms  # elapsed time, in milliseconds
        

        它使用timeit.default_timer(一个平台特定的计时器函数:time.time 用于 Unix 平台,time.clock 用于 Windows 平台)来测量块的挂钟时间。

        【讨论】:

          【解决方案4】:

          查看time.clock() 函数 (http://docs.python.org/library/time.html)

          【讨论】:

          • timeit 最适合测量运行时间
          • 我怎么不知道它的存在?我一直都是自己做的。谢谢,为其他答案 +1。
          猜你喜欢
          • 1970-01-01
          • 2012-08-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多