Python3标准库:time时钟时间
1. time时钟时间
time模块允许访问多种类型的时钟,分别用于不同的用途。标准系统调用(如time())会报告系统“墙上时钟”时间。monotonic()时钟可以用于测量一个长时间运行的进程的耗用时间(elapsed time),因为即使系统时间有改变,也能保证这个时钟不会逆转。对于性能测试,perf_counter()允许访问有最高可用分辨率的时钟,这使得短时间测量更为准确。CPU时间可以通过clock()得到,process_time()会返回处理器时间和系统时间的组合结果。
1.1 比较时钟
时钟的实现细节因平台而异。可以使用get_clock_info()获得当前实现的基本信息,包括时钟的分辨率。
import textwrap import time available_clocks = [ (\'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()) )
monotonic和perf_counter时钟是通过相同的底层系统调用来实现的。
1.2 wall clock time
time模块的核心函数之一是time(),它会把从“纪元”开始以来的秒数作为一个浮点值返回。
import time print(\'The time is:\', time.time())
纪元是时间测量的起始点,对于UNIX系统这个起始时间就是1970年1月1日 0:00。尽管这个值总是一个浮点数,但具体的精度依赖于具体的平台。
浮点数表示对于存储或比较日期很有用,但是对于生成人类刻度的表示就有些差强人意了。要记录或打印时间,ctime()可能是更好的选择。
import time print(\'The time is :\', time.ctime()) later = time.time() + 15 print(\'15 secs from now :\', time.ctime(later))
这个例子中的第二个print()调用显示了如何使用ctime()格式化非当前的时间的另一个时间值。
1.3 单调时钟
由于time()查看系统时钟,并且用户或系统服务可能改变系统时钟来同步多个计算机上的时钟,所以反复调用time()所产生的值可能向前和向后。试图测量持续时间或者使用这些时间来完成计算时,这可能会导致意想不到的行为。为了避免这些情况,可以使用monotonic(),它总是返回向前的值。
import time start = time.monotonic() time.sleep(0.1) end = time.monotonic() print(\'start : {:>9.2f}\'.format(start)) print(\'end : {:>9.2f}\'.format(end)) print(\'span : {:>9.2f}\'.format(end - start))
单调时钟的起始点没有被定义,所以返回值只是在与其他时钟值完成计算时有用。在这个例子中,使用monotonic()来测量睡眠持续时间。
1.4 处理器时钟的时间
time()返回的是一个墙上时钟时间,而clock()返回处理器时钟时间。clock()返回的值反映了程序运行时使用的实际时间。
import hashlib import time # Data to use to calculate md5 checksums data = open(__file__, \'rb\').read() for i in range(5): h = hashlib.sha1() print(time.ctime(), \': {:0.3f} {:0.3f}\'.format( time.time(), time.process_time())) for i in range(300000): h.update(data) cksum = h.digest()
在这个例子中,每次循环迭代时,会打印格式化的ctime()时间,以及time()和clock()返回的浮点值。
一般情况下,如果程序什么也没有做,则处理器时钟不会“滴答”(tick)。
import time template = \'{} - {:0.2f} - {:0.2f}\' print(template.format( time.ctime(), time.time(), time.process_time()) ) for i in range(3, 0, -1): print(\'Sleeping\', i) time.sleep(i) print(template.format( time.ctime(), time.time(), time.process_time()) )
在这个例子中,循环几乎不做什么工作,每次迭代后都会睡眠。应用睡眠时,time()值会增加,而clock()值不会增加。
调用sleep()会从事当前线程交出控制,并要求这个现场等待系统再次将其唤醒。如果程序只有一个线程,则这个函数实际上会阻塞应用,使它不做任何工作。
1.5 性能计数器
在测量性能时,高分辨率时钟是必不可少的。要确定最好的时钟数据源,需要有平台特定的知识,python通过perf_counter()来提供所需的这些知识。
import hashlib import time # Data to use to calculate md5 checksums data = open(__file__, \'rb\').read() loop_start = time.perf_counter() for i in range(5): iter_start = time.perf_counter() h = hashlib.sha1() for i in range(300000): h.update(data) cksum = h.digest() now = time.perf_counter() loop_elapsed = now - loop_start iter_elapsed = now - iter_start print(time.ctime(), \': {:0.3f} {:0.3f}\'.format( iter_elapsed, loop_elapsed))
类似于monotonic(),perf_counter()的纪元未定义,所以返回值值用于比较和计算值,而不作为绝对时间。
1.6 时间组成
有些情况下需要把时间存储为过去了多少秒(秒数),但是另外一些情况下,程序需要访问一个日期的各个字段(例如,年和月)。time模块定义了struct_time来保存日期和时间值,其中分解了各个组成部分以便于访问。很多函数都要处理struct_time值不是浮点值。
import time def show_struct(s): print(\' tm_year :\', s.tm_year) print(\' tm_mon :\', s.tm_mon) print(\' tm_mday :\', s.tm_mday) print(\' tm_hour :\', s.tm_hour) print(\' tm_min :\', s.tm_min) print(\' tm_sec :\', s.tm_sec) print(\' tm_wday :\', s.tm_wday) print(\' tm_yday :\', s.tm_yday) print(\' tm_isdst:\', s.tm_isdst) print(\'gmtime:\') show_struct(time.gmtime()) print(\'\nlocaltime:\') show_struct(time.localtime()) print(\'\nmktime:\', time.mktime(time.localtime()))
gmtime()函数以UTC格式返回当前时间。localtime()会返回应用了当前时区的当前时间。mktime()取一个struct_time实例,将它转换为浮点数表示。
1.7 解析和格式化时间
函数strptime()和strftime()可以在时间值的struct_time表示和字符串表示之间转换。这两个函数支持大量格式化指令,允许不同方式的输入和输出。
下面的这个例子将当前时间从字符串转换为struct_time实例,然后再转换回字符串。
import time def show_struct(s): print(\' tm_year :\', s.tm_year) print(\' tm_mon :\', s.tm_mon) print(\' tm_mday :\', s.tm_mday) print(\' tm_hour :\', s.tm_hour) print(\' tm_min :\', s.tm_min) print(\' tm_sec :\', s.tm_sec) print(\' tm_wday :\', s.tm_wday) print(\' tm_yday :\', s.tm_yday) print(\' tm_isdst:\', s.tm_isdst) now = time.ctime(1483391847.433716) print(\'Now:\', now) parsed = time.strptime(now) print(\'\nParsed:\') show_struct(parsed) print(\'\nFormatted:\', time.strftime("%a %b %d %H:%M:%S %Y", parsed))
输出字符串与输入字符串并不完全相同,因为日期前面加了一个前缀0(由“2”变为”02″)。