c - 为什么 fseeko() 对于大文件比小文件更快?

标签 c performance libc

我在这里得到了一些奇怪的性能结果,我希望 stackoverflow.com 上的人可以对此有所启发!

我的目标是一个程序,我可以用它来测试大搜索是否比小搜索更昂贵......

首先,我通过 dd'ing/dev/zero 创建了两个文件来分隔文件...一个是 1 mb,另一个是 9.8gb...然后我写了这段代码:

#define _LARGE_FILE_API
#define _FILE_OFFSET_BITS 64

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main( int argc, char* argv[] )
{
  struct stat64 fileInfo;
  stat64( argv[1], &fileInfo );

  FILE* inFile = fopen( argv[1], "r" );

  for( int i = 0; i < 1000000; i++ )
    {
      double seekFrac = ((double)(random() % 100)) / ((double)100);

      unsigned long long seekOffset = (unsigned long long)(seekFrac * fileInfo.st_size);

      fseeko( inFile, seekOffset, SEEK_SET );
    }

    fclose( inFile );
}

基本上,此代码会在文件的整个范围内进行一百万次随机搜索。当我在 time 下运行它时,对于 smallfile,我得到了这样的结果:

[developer@stinger ~]# time ./seeker ./smallfile

real    0m1.863s
user    0m0.504s
sys  0m1.358s

当我针对 9.8 gig 文件运行它时,我得到如下结果:

[developer@stinger ~]# time ./seeker ./bigfile

real    0m0.670s
user    0m0.337s
sys  0m0.333s

我对每个文件运行了几十次,结果是一致的。在大文件中查找比在小文件中查找快两倍以上。为什么?

最佳答案

您不是在测量磁盘性能,而是在测量 fseek 设置指针并返回所需的时间。

如果您想测试真实的 IO,我建议您从您要查找的位置读取文件。

关于c - 为什么 fseeko() 对于大文件比小文件更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3267322/

相关文章:

ubuntu - 同一个libc有什么不同? 1.2 1.3 1.4 等

ubuntu - ubuntu 18.04 中的 atom libc-2.31.so 段错误

c - FlexeLint 在 va_list 上抛出错误

c - 收到警告 "assignment makes integer from pointer without a cast"

sql-server - COALESCE 和 ISNULL 哪个更快?

php - 使用 curl 在 PHP 中获取 HTTP 代码

sql - boolean 列上的索引有助于页面缓存

c++ - 使用 libc 的 SIGSEGV 回溯是重复条目

c - 如何使用 Dev-C++ 查看 C 程序的输出?

将十六进制 C 数组转换为 Matlab vector