温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中time库如何使用

发布时间:2021-07-02 15:43:32 阅读:169 作者:Leah 栏目:大数据
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Python中time库如何使用,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

Clocks比较

clock的实现因平台而异,使用getclockinfo可以当前clock实现的基本信息,包括clock的精度。

def clock_basic():    import textwrap    available_clocks = [        ('time', time.time),        ('monotonic', time.monotonic),        ('perf_counter', time.perf_counter),        ('process_time', time.process_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())            )        )

time

time模块的核心函数之一是time(),将epoch开始后的秒数作为浮点数返回。opoch作为时间测量的开始,对于Unix系统而言是:1970年1月1日的0:00,尽管该值是浮点数,实际精度取决于平台。对于时间的存储或者比较,浮点数表示很方便,但是可读性较差,因此对于日志或者打印时间,ctime()方法更有用。

def clock_time():    print (time.time())    print (time.ctime())

单调 Clock

用户或者系统服务为了跨机器同步时钟,会修改系统时钟,time()方法查看的是系统时钟,因此多次调用time()方法,可能会产生向前或者向后的值。当使用这些值进行计算或者试图测量连续时间时,会产生意外行为。monotonic()方法,可以避免这种情况,因为只返回向前的值。

def clock_monotonic():    start = time.monotonic()    time.sleep(0.1)    end = time.monotonic()    print (start)    print (end)

monotonic时钟的开始时间为定义,返回值只能用于与其他时钟值的计算。

处理器时钟

process_time()返回是处理器时钟时间:表示处理器真实的执行时间,因此当程序没有做任何事情的时候,处理器时钟并不会增加。

def processor_clock():    template = '{} - {:.2f} - {:.2f}'    print (template.format(time.ctime(), time.time(), time.process_time()))    for i in range(3, 0, -1):        time.sleep(i)        print (template.format(time.ctime(), time.time(), time.process_time()))

性能计数

高精度的单调时钟对于性能测量非常重要,最佳时钟数据源的确定依赖相关的平台信息,Python在perf_counter中提供了。

def perf_counter_clock():    loop_start = time.perf_counter()    for i in range(5):        iter_start = time.perf_counter()        a = 1        for i in range(10000):            a = a + i        now = time.perf_counter()        loop_elapsed = now - loop_start        iter_elapsed = now - iter_start        print ('{:.6f} {:.6f}'.format(loop_elapsed, iter_elapsed))

看完上述内容,你们掌握Python中time库如何使用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

原文链接:https://my.oschina.net/u/4569567/blog/4429507

AI

开发者交流群×