简体   繁体   English

在Python中,time.time()* 1000是否足够精确?

[英]In Python, is time.time() * 1000 precise enough?

I want to capture timestamps with sub-second precision in python. 我想在python中捕获亚秒精度的时间戳。 It looks like the standard answer is int(time.time() * 1000) 看起来标准答案是int(time.time() * 1000)

However, if time.time() returns a float, won't you have precision problems? 但是,如果time.time()返回一个浮点数,你会不会遇到精度问题? There will be some values that won't represent accurately as a float. 将有一些值不能准确地表示为浮点数。

I'm worried about some fractional times that don't represent correctly as a float, and the timestamp jumping forward or backward in those cases. 我担心一些不能正确表示为float的小数时间,以及在这些情况下向前或向后跳跃的时间戳。

Is that a valid concern? 这是一个有效的问题吗?

If so, what's the work-around? 如果是这样,那么解决方法是什么?

How much precision do you want? 你想要多少精度? While it's true that there are finite decimal fractions that can't be represented as finite binary fractions, the nearest approximate value is going to round to the correct number of integer milliseconds as long as you aren't timing a program running for 143 millenia (2**52 milliseconds). 虽然确实有有限的小数部分不能表示为有限二进制分数,但是只要您没有计算运行143千年的程序,最接近的近似值将四舍五入到正确的整数毫秒数( 2 ** 52毫秒)。

In short: I don't think you need to worry about floating-point precision for this. 简而言之:我不认为你需要担心浮点精度。 You might need to worry about system timer accuracy, precision, or monotonicity, though. 但是,您可能需要担心系统计时器的准确性,精度或单调性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM