Python中的高精度时钟 [英] High-precision clock in Python

查看:56
本文介绍了Python中的高精度时钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Python 中高精度地测量时间——比一秒更精确?我怀疑是否有跨平台的方式来做到这一点;我对 Unix 上的高精度时间很感兴趣,尤其是在 Sun SPARC 机器上运行的 Solaris.

timeit 似乎能够进行高精度的时间测量,但不是测量代码片段需要多长时间,我想直接访问时间值.

解决方案

标准 time.time() 函数提供亚秒级精度,但该精度因平台而异.对于 Linux 和 Mac,精度为 +- 1 微秒或 0.001 毫秒.由于进程中断导致时钟实现问题,Windows 上的 Python 使用 +- 16 毫秒精度.如果您要测量执行时间,timeit 模块可以提供更高的分辨率.

<预><代码>>>>导入时间>>>time.time() #从纪元返回秒数1261367718.971009

Python 3.7 为 time 模块引入了新函数,可提供更高的分辨率:

<预><代码>>>>导入时间>>>时间.time_ns()1530228533161016309>>>time.time_ns()/(10 ** 9) # 转换为浮点秒1530228544.0792289

Is there a way to measure time with high-precision in Python --- more precise than one second? I doubt that there is a cross-platform way of doing that; I'm interesting in high precision time on Unix, particularly Solaris running on a Sun SPARC machine.

timeit seems to be capable of high-precision time measurement, but rather than measure how long a code snippet takes, I'd like to directly access the time values.

解决方案

The standard time.time() function provides sub-second precision, though that precision varies by platform. For Linux and Mac precision is +- 1 microsecond or 0.001 milliseconds. Python on Windows uses +- 16 milliseconds precision due to clock implementation problems due to process interrupts. The timeit module can provide higher resolution if you're measuring execution time.

>>> import time
>>> time.time()        #return seconds from epoch
1261367718.971009      

Python 3.7 introduces new functions to the time module that provide higher resolution:

>>> import time
>>> time.time_ns()
1530228533161016309
>>> time.time_ns() / (10 ** 9) # convert to floating-point seconds
1530228544.0792289

这篇关于Python中的高精度时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆