为何使用O_DIRECT的读取速度慢于普通read操作?
关于O_DIRECT读取性能低于普通read的问题
测试代码
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <malloc.h> int main (int argc, char* argv[]) { int fd; int alignment = 4096; int bufsize = 4096 * 4096; char* buf = (char*) memalign(alignment, bufsize); int i, n, result=0; const char* fname = "1GB.txt"; if ((fd = open(fname, O_RDONLY|O_DIRECT)) < 0) { printf("%s: cannot open %s\n", fname); exit(2); } while ( (n = read(fd,buf,bufsize)) > 0 ) for (i=0; i<n; ++i) result += buf[i]; printf("Result: %d\n", result); return 0; }
执行命令
echo 1 > /proc/sys/vm/drop_caches time ./a.out 1GB.txt
测试结果与调整尝试
刷新页缓存后,不使用O_DIRECT仅需1.1秒,而使用O_DIRECT则需要2.5秒。
尝试过以下调整:
- 将bufsize增大至
4096 * 4096 * 4,运行时间降至1.79秒 - 增大至
4096 * 4096 * 64,时间降至1.75秒 - 将alignment减小至512,时间降至1.72秒
目前不清楚还有哪些调整方向。
疑问
不理解为何使用O_DIRECT会让代码变慢,这会不会和使用磁盘加密有关?
环境信息:Debian 12,内核版本6.1.0-9-amd64。
后续问题
后续相关问题:为什么即使启用预读,O_DIRECT还是比普通read()慢?
内容的提问来源于stack exchange,提问作者1f604
相关产品推荐
相关产品推荐

