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

为何使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 07:43:19