如果我运行以下代码
import os
import time
def check_different_times():
try:
os.remove("temp")
except FileNotFoundError:
pass
with open("temp", "w") as f:
f.write("hi")
first = os.stat("temp").st_mtime_ns
time.sleep(0.001)
with open("temp", "w") as f:
f.write("b")
second = os.stat("temp").st_mtime_ns
return first != second
print(sum(check_different_times() for _ in range(100)))
根据我对unix时间戳工作原理的理解,这应该打印100,因为0.001s是1e6纳秒,所以两个修改时间显然应该不同。
但是,如果我在我的 Ubuntu 笔记本电脑上运行它,它会打印类似 28 或 30 的内容。如果我删除
sleep
行,它会打印类似 1 或 2 的内容。这是 Ubuntu 和 Python 中的一些奇怪的缓冲问题吗? ,或者我对 mtime 的理解存在缺陷?
在 python 3.11 中,
time.sleep()
进行了改进,使其在 Windows 和 Unix 上都更加准确。更新到 python 3.11 可能会解决您的问题。