Python 多次返回相同时间戳的问题

Issue with Python returning same timestamp several times

我正在使用一个 API,它使用回调函数每秒最多发送 2000 次数据。函数的主体获取数据参数(API 调用函数使用),附加时间戳(使用 datetime.now().timestamp()),然后将其发送到队列,获取完成后将保存在文件中的位置。

我面临的问题是我多次获得相同的时间戳,但数据不同。以下是一些已保存数据的示例:

数据------时间戳

3258 1595943590.058758

3246 1595943590.058758

3246 1595943590.058758

3248 1595943590.058758

3254 1595943590.058758

3246 1595943590.058758

我尝试使用 time.time() 代替,但问题仍然存在:

2986 1595944140.3182354

2986 1595944140.3182354

2984 1595944140.3182354

2984 1595944140.3182354

2984 1595944140.3182354

2986 1595944140.3182354

2986 1595944140.3182354

2982 1595944140.3182354

2980 1595944140.3182354

2986 1595944140.3182354

问题是API发送数据太快导致时间更新不够快?有没有更准确的时间获取方式?

#part of a class
def apiFunc(self, data):
        if data:
                d = (data, time.time())
                self.storage.put(d)
                return True
        return False

根据 this answer,windows 上的 time() 只有约 16 毫秒的精度。

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.

也许可以将time.perf_counter的精确度与time.time的意义结合起来。这是代码和输出(左边是纯 time.time,右边是我的建议):

>>> if 1:
    import time
    delta = time.time() - time.perf_counter()
    timestamps = []
    for _ in range(10):
        pure = time.time()
        mine = time.perf_counter() + delta
        timestamps.append((pure, mine))
    for row in timestamps:
        print(row)

(1595947258.0029619, 1595947258.0029738)
(1595947258.0029619, 1595947258.0029812)
(1595947258.0029619, 1595947258.0029826)
(1595947258.0029619, 1595947258.002984)
(1595947258.0029619, 1595947258.0029855)
(1595947258.0029619, 1595947258.0029874)
(1595947258.0029619, 1595947258.0029886)
(1595947258.0029619, 1595947258.00299)
(1595947258.0029619, 1595947258.0029914)
(1595947258.0029619, 1595947258.002993)

摘自更长的输出,其中纯时间最终发生了变化(不得不尝试数千行):

...
(1595947517.2481732, 1595947517.2532165)
(1595947517.2481732, 1595947517.2532175)
(1595947517.2481732, 1595947517.2532187)
(1595947517.256172, 1595947517.2532716)
(1595947517.256172, 1595947517.253275)
(1595947517.256172, 1595947517.253278)
...