程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2024-11(3)

Python3标准库:time时钟时间

发布于2020-03-20 16:14     阅读(1453)     评论(0)     点赞(7)     收藏(2)


作者:@小灰灰
本文为作者原创,转载请注明出处:https://www.cnblogs.com/liuhui0308/p/12372556.html


1. time时钟时间

time模块允许访问多种类型的时钟,分别用于不同的用途。标准系统调用(如time())会报告系统“墙上时钟”时间。monotonic()时钟可以用于测量一个长时间运行的进程的耗用时间(elapsed time),因为即使系统时间有改变,也能保证这个时钟不会逆转。对于性能测试,perf_counter()允许访问有最高可用分辨率的时钟,这使得短时间测量更为准确。CPU时间可以通过clock()得到,process_time()会返回处理器时间和系统时间的组合结果。

1.1 比较时钟

时钟的实现细节因平台而异。可以使用get_clock_info()获得当前实现的基本信息,包括时钟的分辨率。

  1. import textwrap
  2. import time
  3. available_clocks = [
  4. ('monotonic', time.monotonic),
  5. ('perf_counter', time.perf_counter),
  6. ('process_time', time.process_time),
  7. ('time', time.time),
  8. ]
  9. for clock_name, func in available_clocks:
  10. print(textwrap.dedent('''\
  11. {name}:
  12. adjustable : {info.adjustable}
  13. implementation: {info.implementation}
  14. monotonic : {info.monotonic}
  15. resolution : {info.resolution}
  16. current : {current}
  17. ''').format(
  18. name=clock_name,
  19. info=time.get_clock_info(clock_name),
  20. current=func())
  21. )

monotonic和perf_counter时钟是通过相同的底层系统调用来实现的。

1.2 wall clock time 

time模块的核心函数之一是time(),它会把从“纪元”开始以来的秒数作为一个浮点值返回。

  1. import time
  2. print('The time is:', time.time())

纪元是时间测量的起始点,对于UNIX系统这个起始时间就是1970年1月1日 0:00。尽管这个值总是一个浮点数,但具体的精度依赖于具体的平台。

浮点数表示对于存储或比较日期很有用,但是对于生成人类刻度的表示就有些差强人意了。要记录或打印时间,ctime()可能是更好的选择。 

  1. import time
  2. print('The time is :', time.ctime())
  3. later = time.time() + 15
  4. print('15 secs from now :', time.ctime(later))

这个例子中的第二个print()调用显示了如何使用ctime()格式化非当前的时间的另一个时间值。

1.3 单调时钟

由于time()查看系统时钟,并且用户或系统服务可能改变系统时钟来同步多个计算机上的时钟,所以反复调用time()所产生的值可能向前和向后。试图测量持续时间或者使用这些时间来完成计算时,这可能会导致意想不到的行为。为了避免这些情况,可以使用monotonic(),它总是返回向前的值。

  1. import time
  2. start = time.monotonic()
  3. time.sleep(0.1)
  4. end = time.monotonic()
  5. print('start : {:>9.2f}'.format(start))
  6. print('end : {:>9.2f}'.format(end))
  7. print('span : {:>9.2f}'.format(end - start))

单调时钟的起始点没有被定义,所以返回值只是在与其他时钟值完成计算时有用。在这个例子中,使用monotonic()来测量睡眠持续时间。

1.4 处理器时钟的时间

time()返回的是一个墙上时钟时间,而clock()返回处理器时钟时间。clock()返回的值反映了程序运行时使用的实际时间。

  1. import hashlib
  2. import time
  3. # Data to use to calculate md5 checksums
  4. data = open(__file__, 'rb').read()
  5. for i in range(5):
  6. h = hashlib.sha1()
  7. print(time.ctime(), ': {:0.3f} {:0.3f}'.format(
  8. time.time(), time.process_time()))
  9. for i in range(300000):
  10. h.update(data)
  11. cksum = h.digest()

在这个例子中,每次循环迭代时,会打印格式化的ctime()时间,以及time()和clock()返回的浮点值。

一般情况下,如果程序什么也没有做,则处理器时钟不会“滴答”(tick)。

  1. import time
  2. template = '{} - {:0.2f} - {:0.2f}'
  3.  
  4. print(template.format(
  5. time.ctime(), time.time(), time.process_time())
  6. )
  7. for i in range(3, 0, -1):
  8. print('Sleeping', i)
  9. time.sleep(i)
  10. print(template.format(
  11. time.ctime(), time.time(), time.process_time())
  12. )

在这个例子中,循环几乎不做什么工作,每次迭代后都会睡眠。应用睡眠时,time()值会增加,而clock()值不会增加。

调用sleep()会从事当前线程交出控制,并要求这个现场等待系统再次将其唤醒。如果程序只有一个线程,则这个函数实际上会阻塞应用,使它不做任何工作。 

1.5 性能计数器 

在测量性能时,高分辨率时钟是必不可少的。要确定最好的时钟数据源,需要有平台特定的知识,python通过perf_counter()来提供所需的这些知识。

  1. import hashlib
  2. import time
  3. # Data to use to calculate md5 checksums
  4. data = open(__file__, 'rb').read()
  5. loop_start = time.perf_counter()
  6. for i in range(5):
  7. iter_start = time.perf_counter()
  8. h = hashlib.sha1()
  9. for i in range(300000):
  10. h.update(data)
  11. cksum = h.digest()
  12. now = time.perf_counter()
  13. loop_elapsed = now - loop_start
  14. iter_elapsed = now - iter_start
  15. print(time.ctime(), ': {:0.3f} {:0.3f}'.format(
  16. iter_elapsed, loop_elapsed))

类似于monotonic(),perf_counter()的纪元未定义,所以返回值值用于比较和计算值,而不作为绝对时间。

1.6 时间组成

有些情况下需要把时间存储为过去了多少秒(秒数),但是另外一些情况下,程序需要访问一个日期的各个字段(例如,年和月)。time模块定义了struct_time来保存日期和时间值,其中分解了各个组成部分以便于访问。很多函数都要处理struct_time值不是浮点值。

  1. import time
  2. def show_struct(s):
  3. print(' tm_year :', s.tm_year)
  4. print(' tm_mon :', s.tm_mon)
  5. print(' tm_mday :', s.tm_mday)
  6. print(' tm_hour :', s.tm_hour)
  7. print(' tm_min :', s.tm_min)
  8. print(' tm_sec :', s.tm_sec)
  9. print(' tm_wday :', s.tm_wday)
  10. print(' tm_yday :', s.tm_yday)
  11. print(' tm_isdst:', s.tm_isdst)
  12. print('gmtime:')
  13. show_struct(time.gmtime())
  14. print('\nlocaltime:')
  15. show_struct(time.localtime())
  16. print('\nmktime:', time.mktime(time.localtime()))

gmtime()函数以UTC格式返回当前时间。localtime()会返回应用了当前时区的当前时间。mktime()取一个struct_time实例,将它转换为浮点数表示。

1.7 解析和格式化时间

函数strptime()和strftime()可以在时间值的struct_time表示和字符串表示之间转换。这两个函数支持大量格式化指令,允许不同方式的输入和输出。

下面的这个例子将当前时间从字符串转换为struct_time实例,然后再转换回字符串。

  1. import time
  2. def show_struct(s):
  3. print(' tm_year :', s.tm_year)
  4. print(' tm_mon :', s.tm_mon)
  5. print(' tm_mday :', s.tm_mday)
  6. print(' tm_hour :', s.tm_hour)
  7. print(' tm_min :', s.tm_min)
  8. print(' tm_sec :', s.tm_sec)
  9. print(' tm_wday :', s.tm_wday)
  10. print(' tm_yday :', s.tm_yday)
  11. print(' tm_isdst:', s.tm_isdst)
  12. now = time.ctime(1483391847.433716)
  13. print('Now:', now)
  14. parsed = time.strptime(now)
  15. print('\nParsed:')
  16. show_struct(parsed)
  17. print('\nFormatted:',
  18. time.strftime("%a %b %d %H:%M:%S %Y", parsed))

输出字符串与输入字符串并不完全相同,因为日期前面加了一个前缀0(由“2”变为"02")。



所属网站分类: 技术文章 > 博客

作者:sjhjf0293

链接:https://www.pythonheidong.com/blog/article/271500/1a68d3e95583a9531351/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

7 0
收藏该文
已收藏

评论内容:(最多支持255个字符)