如何在Python中计时一批代码的执行时间? [英] How to time execution time of a batch of code in Python?

查看:28
本文介绍了如何在Python中计时一批代码的执行时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found this question and answer here on StackOverflow.

Python - time.clock() vs. time.time() -准确性?

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

Here is some code I'm trying to run:

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 一个参数保存在别处的函数?

How would I give timeit a function with a parameter that's been saved elsewhere?

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

This is something I've written in Ruby that gave me results in clean code, maybe this helps for suggestions.

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 编写时间测量代码的方式:

This is how I typically write time measurement code in 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() 是跨平台且可靠的.

As mentioned in the post you linked to, time.clock() is not appropriate for measuring elapsed time since it reports the amount of CPU time used by your process only (at least on Unix systems). Using time.time() is cross-platform and reliable.

这篇关于如何在Python中计时一批代码的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆