【问题标题】:How to time execution time of a batch of code in Python?如何在 Python 中计时一批代码的执行时间?
【发布时间】:2012-01-17 02:47:17
【问题描述】:

我在 StackOverflow 上找到了这个问题和答案。

Python - time.clock() vs. time.time() - accuracy?

这是我正在尝试运行的一些代码:

import sys
import time
import timeit

if (len(sys.argv) > 1):
  folder_path = sys.argv[1]
  if not os.path.isdir(folder_path):
    print "The folder you provided doesn't exist"    
  else:
    print_console_headers()    
    rename_files_to_title_case(folder_path)
    #start the timer.
    #do some freaky magic here.
    #end the timer.

else:
  print "You must provide a path to a folder."

def print_console_headers():
  print "Renaming files..."
  print "--------------------"
  return

def rename_files_to_title_case():  
  """this is just for testing purposes"""  
  L = []
  for i in range(100):
      L.append(i)

if __name__ == '__main__':
    from timeit import Timer
    t = Timer("test()", "from __main__ import test")
    print t.timeit()

如何给 timeit 一个带有已保存在别处的参数的函数?

这是我用 Ruby 编写的东西,它给我的结果是干净的代码,也许这有助于提供建议。

start_time = Time.now

folder_path = ARGV[0]
i = 0
Dir.glob(folder_path + "/*").sort.each do |f|
    filename = File.basename(f, File.extname(f))
    File.rename(f, folder_path + "/" + filename.gsub(/\b\w/){$&.upcase} + File.extname(f))
    i += 1
end

puts "Renaming complete."
puts "The script renamed #{i} file(s) correctly."
puts "----------"
puts "Running time is #{Time.now - start_time} seconds"

【问题讨论】:

    标签: python time


    【解决方案1】:

    我会使用计时装饰器并将您想要计时的代码放入函数中。

    import time
    
    def timeit(f):
    
        def timed(*args, **kw):
    
            ts = time.time()
            result = f(*args, **kw)
            te = time.time()
    
            print 'func:%r args:[%r, %r] took: %2.4f sec' % \
              (f.__name__, args, kw, te-ts)
            return result
    
        return timed
    

    无论是使用注解,还是使用装饰器都很容易。

    @timeit
    def compute_magic(n):
         #function definition
         #....
    

    或者为你想要计时的函数重新命名。

    compute_magic = timeit(compute_magic)
    

    我的博文有更多信息。 http://blog.mattalcock.com/2013/2/24/timing-python-code/

    【讨论】:

      【解决方案2】:

      这就是我通常在 Python 中编写时间测量代码的方式:

      start_time = time.time()
      
      # ... do stuff
      
      end_time = time.time()
      print("Elapsed time was %g seconds" % (end_time - start_time))
      

      正如您链接到的帖子中提到的,time.clock() 不适合测量经过的时间,因为它仅报告 您的 进程使用的 CPU 时间量(至少在 Unix 系统上)。使用time.time() 是跨平台且可靠的。

      【讨论】:

      • timeit uses time.clock() on Windows。 from timeit import default_timer as timer; start_time = timer(); ... 允许在 *nix 上的 time.time() 和 Windows 上的 time.clock() 之间自动或以后切换它可能会使用 time.walltime()。
      • @J.F.Sebastian:我不认为 OP 正在寻找 time.clock() 的功能,这就是为什么我认为 timeit 不是一个合适的选择。
      • 在 Windows time.clock() 上测量 walltime,即您的评论:“它仅报告您的进程使用的 CPU 时间量。” 可能不正确。
      • @J.F.Sebastian:确实如此。我已经澄清了我的答案。
      • 现在 this 是一个很好的答案,而不是之前给出的“Google it”精英“答案”。
      【解决方案3】:

      如果你需要测量函数内特定代码行的计时,当装饰器帮不上忙时有一个解决方案

      import time
      from time import sleep
      
      class TT(object):
          def __init__(self):
              self.start = time.time()
          def __str__(self):
              return str(time.time() - self.start)
      
      
      timeit = TT()
      
      sleep(1)
      print timeit
      
      sleep(2)
      print timeit
      

      将打印:

      1.0
      3.00
      

      【讨论】:

        【解决方案4】:

        对函数计时的一种有趣方法是使用装饰器和包装器函数。我为此使用的功能之一是:

        import time
        
        def print_timing(func):
            def wrapper(*arg):
                t1 = time.time()
                res = func(*arg)
                t2 = time.time()
                string = '| %s took %0.3f ms |' % (func.func_name, (t2-t1)*1000.0)
                print
                print '-'*len(string)
                print string
                print '-'*len(string)
                print
                return res
            return wrapper
        

        任何由@print_timing 修饰的函数,都会打印输出到标准输出的时间

        @print_timing
        def some_function(text):
            print text
        

        这使得为特定功能计时非常方便。

        【讨论】:

          猜你喜欢
          • 2012-11-02
          • 2010-12-24
          • 2023-03-16
          • 1970-01-01
          • 1970-01-01
          • 2011-11-21
          • 2021-06-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多