如何在Python中计时一段代码的执行时间?
我在StackOverflow上找到了这个问题和答案。
Python - time.clock() 和 time.time() 的准确性对比?
这是我正在尝试运行的一段代码:
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"
4 个回答
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
这样就很方便地可以测量特定函数的执行时间了。
16
我会使用一个计时装饰器,把你想要计时的代码放进一个函数里。
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/
35
这是我通常在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()
则是跨平台的,并且更可靠。