2012-09-16 47 views
12

基本上,我希望能够输出应用程序运行所花费的时间。我想我需要使用某种时间功能,但我不确定哪一种。我正在寻找类似以下的东西...我的Python应用程序需要多长时间才能运行?

START MY TIMER 
code for application 
more code 
more code 
etc 
STOP MY TIMER 

OUTPUT ELAPSED在定时器的启动和停止之间做上述代码的时间。思考?

回答

0

你不能只是得到当前系统时间的开始和结束时,再从最后的时间减去开始时间?

18

做到这一点,最简单的方法就是把:

import time 
start_time = time.time() 

开始和

print "My program took", time.time() - start_time, "to run" 

末。

+0

谢谢。完美工作。 – user1675111

1

如果您运行的是Mac OS X或Linux,只需使用time实用程序:

$ time python script.py 
real 0m0.043s 
user 0m0.027s 
sys  0m0.013s 

如果不是,请使用time模块:

import time 

start_time = time.time() 

# ... 

print time.time() - start_time, 's' 
3

您可以使用系统命令time

[email protected]:~# time python test.py 
hello world! 

real 0m0.015s 
user 0m0.008s 
sys  0m0.007s 
+1

我喜欢这个,除了这将包括任何“开销”的进口和初始化你不想测试,在计时片段的情况下。在windows上的 – Ian

+0

时间不起作用 – George

8

为了在不同平台上获得最佳效果:

from timeit import default_timer as timer 

# START MY TIMER 
start = timer() 
code for application 
more code 
more code 
etc 
# STOP MY TIMER 
elapsed_time = timer() - start # in seconds 

timer()是在Python 3.3 time.perf_counter()time.clock()/time.time()在Windows /其他相应平台的旧版本。

相关问题