我有一个程序说:
for i in xrange(10):
for p in xrange(10):
print i, p
我希望能够打印程序在程序结束时执行的时间(以毫秒为单位)。
答案 0 :(得分:4)
使用python -m timeit -s 'import my_module' 'my_module.do_stuff()'
运行程序以查看运行时间信息。
根据timeit
documentation,只需滚动自己就有点棘手了,所以它是为你提供的。
答案 1 :(得分:3)
以下是如何在python代码中执行此操作,尽管我更喜欢@Julian的方法,只是将其作为替代方法提供:
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
答案 2 :(得分:1)
我已经编写了一个小片段,可以让您使用上下文管理器测量已用时间。看看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平台)来测量块的挂钟时间。
答案 3 :(得分:0)
查看time.clock()
函数(http://docs.python.org/library/time.html)