perf_counter 返回时间错误

perf_counter is returning wrong time

我运行这个简单的代码:

import time
print(time.perf_counter())

但由于某种原因,输出为 9851.549930951。 代码用不到一秒就运行,而且我没有使用perf_counter_ns。这在其他程序中也是一个问题。 perf_counter 线程完成执行所需的秒数输出 9000+ 而不是 0.9。输出总是很快,但答案总是 9000+,如 9851.549930951.

你读过文档了吗? time.perf_counter()

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid. (emphasis mine)

所以你这样做:

import time

start = time.perf_counter()

# ....

print (time.perf_counter() - start)

为了获得更好的性能测量(多次运行的平均值),您可能需要查看 timeit