我有一个Python命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。
我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。
我有一个Python命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。
我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。
当前回答
我也喜欢Paul McGuire的回答,并提出了一个更符合我需求的上下文管理器表单。
import datetime as dt
import timeit
class TimingManager(object):
"""Context Manager used with the statement 'with' to time some execution.
Example:
with TimingManager() as t:
# Code to time
"""
clock = timeit.default_timer
def __enter__(self):
"""
"""
self.start = self.clock()
self.log('\n=> Start Timing: {}')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""
"""
self.endlog()
return False
def log(self, s, elapsed=None):
"""Log current time and elapsed time if present.
:param s: Text to display, use '{}' to format the text with
the current time.
:param elapsed: Elapsed time to display. Dafault: None, no display.
"""
print s.format(self._secondsToStr(self.clock()))
if(elapsed is not None):
print 'Elapsed time: {}\n'.format(elapsed)
def endlog(self):
"""Log time for the end of execution with elapsed time.
"""
self.log('=> End Timing: {}', self.now())
def now(self):
"""Return current elapsed time as hh:mm:ss string.
:return: String.
"""
return str(dt.timedelta(seconds = self.clock() - self.start))
def _secondsToStr(self, sec):
"""Convert timestamp to h:mm:ss string.
:param sec: Timestamp.
"""
return str(dt.datetime.fromtimestamp(sec))
其他回答
time.clock()
自3.3版起已弃用:此函数的行为取决于在平台上:改用perf_counter()或process_time(),这取决于您的需求,以具有定义良好的行为。
time.perf_counter()
返回性能计数器的值(以秒为单位),即具有最高可用分辨率的时钟来测量短路期间它包括睡眠期间的时间系统范围内。
time.process_time()
返回系统和当前进程的用户CPU时间。它不包括经过的时间在睡眠期间。
start = time.process_time()
... do something
elapsed = (time.process_time() - start)
Python中最简单的方法:
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
这假设程序运行至少需要十分之一秒。
打印:
--- 0.764891862869 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
如果您想以微秒为单位测量时间,那么可以使用以下版本,完全基于Paul McGuire和Nicojo的答案——这是Python 3代码。我还为它添加了一些颜色:
import atexit
from time import time
from datetime import timedelta, datetime
def seconds_to_str(elapsed=None):
if elapsed is None:
return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
else:
return str(timedelta(seconds=elapsed))
def log(txt, elapsed=None):
colour_cyan = '\033[36m'
colour_reset = '\033[0;0;39m'
colour_red = '\033[31m'
print('\n ' + colour_cyan + ' [TIMING]> [' + seconds_to_str() + '] ----> ' + txt + '\n' + colour_reset)
if elapsed:
print("\n " + colour_red + " [TIMING]> Elapsed time ==> " + elapsed + "\n" + colour_reset)
def end_log():
end = time()
elapsed = end-start
log("End Program", seconds_to_str(elapsed))
start = time()
atexit.register(end_log)
log("Start Program")
log()=>打印定时信息的函数。
txt==>要记录的第一个参数及其用于标记计时的字符串。
atexit==>Python模块,用于注册程序退出时可以调用的函数。
这是保罗·麦奎尔的回答,对我来说很有用。以防有人在运行这个问题时遇到问题。
import atexit
from time import clock
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
value = next(it)
else:
value = initializer
for element in it:
value = function(value, element)
return value
def secondsToStr(t):
return "%d:%02d:%02d.%03d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(t*1000,),1000,60,60])
line = "="*40
def log(s, elapsed=None):
print (line)
print (secondsToStr(clock()), '-', s)
if elapsed:
print ("Elapsed time:", elapsed)
print (line)
def endlog():
end = clock()
elapsed = end-start
log("End Program", secondsToStr(elapsed))
def now():
return secondsToStr(clock())
def main():
start = clock()
atexit.register(endlog)
log("Start Program")
导入文件后,从程序中调用timing.main()。