我有一个Python命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。
我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。
我有一个Python命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。
我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。
当前回答
只需使用timeit模块。它同时适用于Python 2和Python 3。
import timeit
start = timeit.default_timer()
# All the program statements
stop = timeit.default_timer()
execution_time = stop - start
print("Program Executed in "+str(execution_time)) # It returns time in seconds
它在几秒钟内返回,您可以获得执行时间。这很简单,但您应该在启动程序执行的主函数中编写这些。如果您想获得执行时间,即使在出现错误时,也可以将参数“Start”设置为它,并在那里进行如下计算:
def sample_function(start,**kwargs):
try:
# Your statements
except:
# except statements run when your statements raise an exception
stop = timeit.default_timer()
execution_time = stop - start
print("Program executed in " + str(execution_time))
其他回答
只需使用timeit模块。它同时适用于Python 2和Python 3。
import timeit
start = timeit.default_timer()
# All the program statements
stop = timeit.default_timer()
execution_time = stop - start
print("Program Executed in "+str(execution_time)) # It returns time in seconds
它在几秒钟内返回,您可以获得执行时间。这很简单,但您应该在启动程序执行的主函数中编写这些。如果您想获得执行时间,即使在出现错误时,也可以将参数“Start”设置为它,并在那里进行如下计算:
def sample_function(start,**kwargs):
try:
# Your statements
except:
# except statements run when your statements raise an exception
stop = timeit.default_timer()
execution_time = stop - start
print("Program executed in " + str(execution_time))
我使用来自ttictoc的tic和toc。
pip install ttictoc
然后可以在脚本中使用:
from ttictoc import tic,toc
tic()
# foo()
print(toc())
要使用metakermit对Python 2.7的更新答案,您需要单调包。
代码如下:
from datetime import timedelta
from monotonic import monotonic
start_time = monotonic()
end_time = monotonic()
print(timedelta(seconds=end_time - start_time))
我尝试使用以下脚本找到时间差。
import time
start_time = time.perf_counter()
[main code here]
print (time.perf_counter() - start_time, "seconds")
在Linux或Unix中:
$ time python yourprogram.py
在Windows中,请参阅StackOverflow问题:如何在Windows命令行上测量命令的执行时间?
对于更详细的输出,
$ time -v python yourprogram.py
Command being timed: "python3 yourprogram.py"
User time (seconds): 0.08
System time (seconds): 0.02
Percent of CPU this job got: 98%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.10
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 9480
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 1114
Voluntary context switches: 0
Involuntary context switches: 22
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0