在 CentOS(以及大多数 Linux 发行版)上,readdir / readdir() 相关性能“差”通常不是系统本身的问题,而是使用方式、文件系统、内核版本、glibc 实现等多方面因素共同导致的。下面按常见原因系统性说明。
readdir() 并不是一次性读取整个目录,而是:
getdents / getdents64 系统调用批量读取所以:
单次 readdir 很快,但“遍历大目录”会慢
例如一个目录有:
问题来源:
✅ 表现:
ls 慢find 慢readdir 循环慢✅ 解决:
不同文件系统对目录遍历性能差异很大:
| 文件系统 | readdir 性能 |
|---|---|
| ext4 | 一般 |
| xfs | 较好(大目录更优) |
| btrfs | 目录大时明显下降 |
| NFS | 非常慢 |
| overlayfs | 额外开销 |
✅ 建议:
readdir在 CentOS 上 NFS + readdir 是经典性能坑:
原因:
✅ 表现:
ls -l 比 ls 更慢(stat 放大)✅ 解决:
actimeo= 调整缓存CentOS 默认 glibc:
readdir 缓冲约 32KB后果:
✅ 替代方案:
getdents64 直接调用很多人误以为:
while ((entry = readdir(dir))) {
stat(entry->d_name, &st);
}
慢是 readdir 的问题,其实是:
stat✅ 优化:
readdir + d_type(如果支持)scandirstatx(新内核)CentOS 默认:
vfs_cache_pressure 偏高结果:
✅ 检查:
free -h
cat /proc/sys/vm/vfs_cache_pressure
✅ 调整:
sysctl -w vm.vfs_cache_pressure=50
在 CentOS 上:
都会:
✅ 验证方式:
getenforce
systemctl status auditd
如果是:
readdir 会直接受限于磁盘随机读。
✅ 表现:
iowait 高top 中 CPU 不忙但程序卡strace -c your_program
df -hT
mount | grep nfs
ls | wc -l
iostat -x 1
CentOS 上 readdir 性能差,90% 是因为“目录太大 + 文件系统不合适 + 后续 stat/io 放大”,而不是 readdir 本身。
如果你愿意,可以告诉我:
我可以直接给你针对性优化方案或代码示例。