4.1 时钟时间
time模块允许访问多种类型的时钟,分别用于不同的用途。标准系统调用(如time())会报告系统"墙上时钟"时间。monotonic()时钟可以用于测量一个长时间运行的进程的耗用时间(elapsed time),因为即使系统时间有改变,也能保证这个时钟不会逆转。对于性能测试,perf_counter()允许访问有最高可用分辨率的时钟,这使得短时间测量更为准确。CPU时间可以通过clock()得到,process_time()会返回处理器时间和系统时间的组合结果。
4.1.1 比较时钟
时钟的实现细节因平台而异。可以使用get_clock_info()获得当前实现的基本信息,包括时钟的分辨率。
import textwrap
import time
available_clocks = [
('clock',time.clock),
('monotonic',time.monotonic),
('perf_counter',time.perf_counter),
('process_time',time.process_time),
('time',time.time),
]
for clock_name,func in available_clocks:
print(textwrap.dedent('''\
{name}:
adjustable : {info.adjustable}
implementation: {info.implementation}
monotonic : {info.monotonic}
resolution : {info.resolution}
current : {current}
''').format(
name = clock_name,
info = time.get_clock_info(clock_name),
current = func())
)
下面在WIN 7上的输出显示,monotonic和perf_counter时钟是通过相同的底层系统调用来实现的。
运行结果: