基本上,我希望能够输出应用程序运行所花费的时间。我想我需要使用某种时间功能,但我不确定哪一种。我正在寻找类似以下的东西...我的Python应用程序需要多长时间才能运行?
START MY TIMER
code for application
more code
more code
etc
STOP MY TIMER
OUTPUT ELAPSED在定时器的启动和停止之间做上述代码的时间。思考?
基本上,我希望能够输出应用程序运行所花费的时间。我想我需要使用某种时间功能,但我不确定哪一种。我正在寻找类似以下的东西...我的Python应用程序需要多长时间才能运行?
START MY TIMER
code for application
more code
more code
etc
STOP MY TIMER
OUTPUT ELAPSED在定时器的启动和停止之间做上述代码的时间。思考?
你不能只是得到当前系统时间的开始和结束时,再从最后的时间减去开始时间?
做到这一点,最简单的方法就是把:
import time
start_time = time.time()
开始和
print "My program took", time.time() - start_time, "to run"
末。
如果您运行的是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'
您可以使用系统命令time
:
[email protected]:~# time python test.py
hello world!
real 0m0.015s
user 0m0.008s
sys 0m0.007s
为了在不同平台上获得最佳效果:
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 /其他相应平台的旧版本。
谢谢。完美工作。 – user1675111