在 CentOS(或其他 Linux 系统)上提升 readdir(目录遍历)效率,通常可以从系统调用方式、文件系统、目录结构、编程语言实现几个层面来优化。下面按实用角度总结:
getdents / getdents64readdir 底层是 getdents64 封装,但 glibc 的 readdir 每次只返回一个条目,频繁系统调用开销大。
✅ 优化方式:
syscall(SYS_getdents64, ...)示例(C):
#include <sys/syscall.h>
#include <unistd.h>
#include <linux/dirent.h>
syscall(SYS_getdents64, fd, buf, sizeof(buf));
适合:
openat() + fd 避免路径解析int dfd = open(dir, O_RDONLY | O_DIRECTORY);
getdents64(dfd, buf, size);
减少路径查找开销。
while (readdir)
stat(file); // 每个文件一次 stat
d_type(readdir 返回的 dirent 有 d_type)if (entry->d_type == DT_REG)
✅ 优点:
| 文件系统 | 说明 |
|---|---|
| XFS | 大目录性能最好(推荐) |
| ext4 | 小目录 OK,大目录一般 |
| NFS | ❌ 极慢,避免大目录 |
CentOS 推荐:
mkfs.xfs /dev/sdX
❌ 一个目录 100 万文件
✅ 拆分目录(hash / 日期 / 前缀)
示例:
/data/ab/abcxxx
/data/2026/01/xx
mount -o noatime,nodiratime /dev/sdX /data
避免每次访问更新 atime。
sysctl -w vfs_cache_pressure=50
(默认 100,越小越倾向缓存目录项)
getdents64std::filesystem::directory_iterator(较慢)❌ 慢:
os.listdir + os.stat
✅ 快:
import os
for name, type in scandir:
if type == 'file':
使用 os.scandir()(Python 3.5+)
少 stat、用 getdents、XFS、拆目录,是 CentOS 提升 readdir 效率的核心。
如果你有:
我可以给你针对性代码示例。