You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无缓冲且已调用file.flush()时,file.close()仍运行缓慢?

问题

为何在无缓冲且已调用file.flush()的情况下,file.close()仍运行缓慢?

测试代码

from time import perf_counter
t = perf_counter()
file = open('dummy', 'wb', buffering=0)
print('open', perf_counter() - t)
t = perf_counter()
file.write(bytes(16 * 1024 ** 2))
print('write 16MB', perf_counter() - t)
t = perf_counter()
file.flush()
print('flush', perf_counter() - t)
t = perf_counter()
file.close()
print('close', perf_counter() - t)

测试输出

open 0.00242589320987463
write 16MB 0.010545279830694199
flush 1.0263174772262573e-06
close 0.033106833696365356

分析推测

这应该是由操作系统页缓存(OS page cache)导致的,但Python不支持O_DIRECT(除非使用mmap),因为O_DIRECT要求内存对齐。

更快存储设备测试

在挂载于/data的更快存储设备上测试后,结果如下:

open 0.001985272392630577
write 16MB 0.009873169474303722
flush 1.1473894119262695e-06
close 0.006200509145855904

系统信息

> uname -srvmpio
Linux 5.15.0-78-generic #85~20.04.1-Ubuntu SMP Mon Jul 17 09:42:39 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux
> cat /proc/mounts | grep '/ '
/dev/sda2 / ext4 rw,relatime,errors=remount-ro 0 0
> cat /proc/mounts | grep '/data '
/dev/nvme0n1 /data ext4 rw,relatime,stripe=32 0 0
> uname -a

内容的提问来源于Stack Exchange,提问作者YouJiacheng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 19:25:05