【问题标题】:What is the best efficient way to read millions of integers separated by lines from text file in c++在 c++ 中从文本文件中读取数百万个由行分隔的整数的最佳有效方法是什么
【发布时间】:2013-02-27 15:31:50
【问题描述】:

我的文本文件中有大约 2500 万个整数,由行分隔。我的第一个任务是获取这些整数并对其进行排序。我实际上已经实现了读取整数并将它们放入数组中(因为我的排序函数将未排序的数组作为参数)。但是,从文件中读取整数是一个非常漫长且昂贵的过程。我已经搜索了许多其他解决方案以获得更便宜和有效的方法,但我无法找到一种能够处理这种尺寸的解决方案。因此,您的建议是从巨大的(约 260MB)文本文件中读取整数。以及如何有效地获得相同问题的行数。

ifstream myFile("input.txt");

int currentNumber;
int nItems = 25000000;
int *arr = (int*) malloc(nItems*sizeof(*arr));
int i = 0;
while (myFile >> currentNumber)
{
    arr[i++] = currentNumber;
}

这就是我从文本文件中获取整数的方式。这并不复杂。我假设行数是固定的(实际上是固定的)

顺便说一句,它当然不会太慢。在配备 2.2GHz i7 处理器的 OS X 中,它在大约 9 秒内完成读取。但我觉得它可能会好得多。

【问题讨论】:

  • 请提供一些代码。读取 2500 万个整数应该不会太慢。
  • 我假设你正在为这个数组预分配内存?或者你如何确保它足够大以容纳内容?
  • 你也分析过你的代码,你确定阅读是瓶颈吗?
  • 我可能会使用sort -nwc 等命令行工具,而不是编写程序。
  • @FredLarson:可能是程序文件加载/处理的初始部分

标签: c++ performance file-io fstream


【解决方案1】:

很可能,对此进行的任何优化都可能收效甚微。在我的机器上,读取大文件的限制因素是磁盘传输速度。是的,提高读取速度可以稍微提高一点,但很可能,你不会从中得到很多。

我在之前的测试中发现 [我会看看是否可以在其中找到答案 - 我在“SO 的实验代码”目录中找不到源代码] 最快的方法是加载文件使用mmap。但它只比使用ifstream 快一点。

编辑:我自制的以几种不同方式读取文件的基准。 getline while reading a file vs reading whole file and then splitting based on newline character

与往常一样,基准衡量的是基准衡量的内容,对环境或代码编写方式的微小更改有时会产生很大的不同。

编辑: 以下是“从文件中读取数字并将其存储在向量中”的一些实现:

#include <iostream>
#include <fstream>
#include <vector>
#include <sys/time.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>


using namespace std;

const char *file_name = "lots_of_numbers.txt";

void func1()
{
    vector<int> v;
    int num;
    ifstream fin(file_name);
    while( fin >> num )
    {
    v.push_back(num);
    }
    cout << "Number of values read " << v.size() << endl;
}


void func2()
{
    vector<int> v;
    v.reserve(42336000);
    int num;

    ifstream fin(file_name);
    while( fin >> num )
    {
    v.push_back(num);
    }
    cout << "Number of values read " << v.size() << endl;
}

void func3()
{
    int *v = new int[42336000];
    int num;

    ifstream fin(file_name);
    int i = 0;
    while( fin >> num )
    {
    v[i++] = num;
    }
    cout << "Number of values read " << i << endl;
    delete [] v;
}


void func4()
{
    int *v = new int[42336000];
    FILE *f = fopen(file_name, "r");
    int num;
    int i = 0;
    while(fscanf(f, "%d", &num) == 1)
    {
    v[i++] = num;
    }
    cout << "Number of values read " << i << endl;
    fclose(f);
    delete [] v;
}    

void func5()
{
    int *v = new int[42336000];
    int num = 0;

    ifstream fin(file_name);
    char buffer[8192];
    int i = 0;
    int bytes = 0;
    char *p;
    int hasnum = 0;
    int eof = 0;
    while(!eof)
    {
    fin.read(buffer, sizeof(buffer));
    p = buffer;
    bytes = 8192;
    while(bytes > 0)
    {
        if (*p == 26)   // End of file marker...
        {
        eof = 1;
        break;
        }
        if (*p == '\n' || *p == ' ')
        {
        if (hasnum)
            v[i++] = num;
        num = 0;
        p++;
        bytes--;
        hasnum = 0;
        }
        else if (*p >= '0' &&  *p <= '9')
        {
        hasnum = 1;
        num *= 10;
        num += *p-'0';
        p++;
        bytes--;
        }
        else 
        {
        cout << "Error..." << endl;
        exit(1);
        }
    }
    memset(buffer, 26, sizeof(buffer));  // To detect end of files. 
    }
    cout << "Number of values read " << i << endl;
    delete [] v;
}

void func6()
{
    int *v = new int[42336000];
    int num = 0;

    FILE *f = fopen(file_name, "r");
    char buffer[8192];
    int i = 0;
    int bytes = 0;
    char *p;
    int hasnum = 0;
    int eof = 0;
    while(!eof)
    {
    fread(buffer, 1, sizeof(buffer), f);
    p = buffer;
    bytes = 8192;
    while(bytes > 0)
    {
        if (*p == 26)   // End of file marker...
        {
        eof = 1;
        break;
        }
        if (*p == '\n' || *p == ' ')
        {
        if (hasnum)
            v[i++] = num;
        num = 0;
        p++;
        bytes--;
        hasnum = 0;
        }
        else if (*p >= '0' &&  *p <= '9')
        {
        hasnum = 1;
        num *= 10;
        num += *p-'0';
        p++;
        bytes--;
        }
        else 
        {
        cout << "Error..." << endl;
        exit(1);
        }
    }
    memset(buffer, 26, sizeof(buffer));  // To detect end of files. 
    }
    fclose(f);
    cout << "Number of values read " << i << endl;
    delete [] v;
}


void func7()
{
    int *v = new int[42336000];
    int num = 0;

    FILE *f = fopen(file_name, "r");
    int ch;
    int i = 0;
    int hasnum = 0;
    while((ch = fgetc(f)) != EOF)
    {
    if (ch == '\n' || ch == ' ')
    {
        if (hasnum)
        v[i++] = num;
        num = 0;
        hasnum = 0;
    }
    else if (ch >= '0' &&  ch <= '9')
    {
        hasnum = 1;
        num *= 10;
        num += ch-'0';
    }
    else 
    {
        cout << "Error..." << endl;
        exit(1);
    }
    }
    fclose(f);
    cout << "Number of values read " << i << endl;
    delete [] v;
}


void func8()
{
    int *v = new int[42336000];
    int num = 0;

    int f = open(file_name, O_RDONLY);

    off_t size = lseek(f, 0, SEEK_END);
    char *buffer = (char *)mmap(NULL, size, PROT_READ, MAP_PRIVATE, f, 0);

    int i = 0;
    int hasnum = 0;
    int bytes = size;
    char *p = buffer;
    while(bytes > 0)
    {
    if (*p == '\n' || *p == ' ')
    {
        if (hasnum)
        v[i++] = num;
        num = 0;
        p++;
        bytes--;
        hasnum = 0;
    }
    else if (*p >= '0' &&  *p <= '9')
    {
        hasnum = 1;
        num *= 10;
        num += *p-'0';
        p++;
        bytes--;
    }
    else 
    {
        cout << "Error..." << endl;
        exit(1);
    }
    }
    close(f);
    munmap(buffer, size);
    cout << "Number of values read " << i << endl;
    delete [] v;
}






struct bm
{
    void (*f)();
    const char *name;
};

#define BM(f) { f, #f }

bm b[] = 
{
    BM(func1),
    BM(func2),
    BM(func3),
    BM(func4),
    BM(func5),
    BM(func6),
    BM(func7),
    BM(func8),
};


double time_to_double(timeval *t)
{
    return (t->tv_sec + (t->tv_usec/1000000.0)) * 1000.0;
}

double time_diff(timeval *t1, timeval *t2)
{
    return time_to_double(t2) - time_to_double(t1);
}



int main()
{
    for(int i = 0; i < sizeof(b) / sizeof(b[0]); i++)
    {
    timeval t1, t2;
    gettimeofday(&t1, NULL);
    b[i].f();
    gettimeofday(&t2, NULL);
    cout << b[i].name << ": " << time_diff(&t1, &t2) << "ms" << endl;
    }
    for(int i = sizeof(b) / sizeof(b[0])-1; i >= 0; i--)
    {
    timeval t1, t2;
    gettimeofday(&t1, NULL);
    b[i].f();
    gettimeofday(&t2, NULL);
    cout << b[i].name << ": " << time_diff(&t1, &t2) << "ms" << endl;
    }
}

结果(连续两次运行,向前和向后以避免文件缓存的好处):

Number of values read 42336000
func1: 6068.53ms
Number of values read 42336000
func2: 6421.47ms
Number of values read 42336000
func3: 5756.63ms
Number of values read 42336000
func4: 6947.56ms
Number of values read 42336000
func5: 941.081ms
Number of values read 42336000
func6: 962.831ms
Number of values read 42336000
func7: 2572.4ms
Number of values read 42336000
func8: 816.59ms
Number of values read 42336000
func8: 815.528ms
Number of values read 42336000
func7: 2578.6ms
Number of values read 42336000
func6: 948.185ms
Number of values read 42336000
func5: 932.139ms
Number of values read 42336000
func4: 6988.8ms
Number of values read 42336000
func3: 5750.03ms
Number of values read 42336000
func2: 6380.36ms
Number of values read 42336000
func1: 6050.45ms

总之,正如有人在 cmets 中指出的那样,整数的实际解析占整个时间的相当大一部分,因此读取文件并不像我最初所说的那么重要。即使是一种非常幼稚的文件读取方式(使用fgetc()ifstream operator&gt;&gt; 更胜一筹。

可以看出,使用mmap 加载文件比通过fstream 读取文件要快一些,但只是稍微快一点。

【讨论】:

  • 我投了反对票,因为此类声明必须有参考资料。请提供它们,我会投票。
  • “读取大文件的限制因素是磁盘传输速度”——这就是为什么 Google 通常会处理分布在集群上的不大于 64 MGb 的文件。
  • 我添加了一个链接,指向一个类似问题的先前答案,这是我上面陈述的基础。
  • @MatsPetersson 您站点的基准测试是将数据分解为几行;他正在解析整数,这需要更多的 CPU。我仍然认为限制因素将是磁盘带宽,但我只是猜测。 (我的猜测是基于系统不可能缓存文件的重要部分,每次访问大约需要 10 毫秒。你可以在 10 毫秒内完成大量的解析。)
  • @MatsPetersson 我看到了你的数字。并同意你的看法。我用getline 尝试了你的方法,用&gt;&gt; 尝试了你的方法,你的方法快了两倍,但它们都“使用ifstream”。所以有不同的方式来使用ifstream,这确实会有所作为。
【解决方案2】:

您可以使用external sorting 对文件中的值进行排序,而无需将它们全部加载到内存中。排序速度将受到您的硬盘驱动器能力的限制,但您将能够处理非常大的文件。这是implementation

【讨论】:

    【解决方案3】:

    尝试读取整数块并解析这些块,而不是逐行读取。

    【讨论】:

    • C++ 库已经可以一次读取 4K 或更大的块了。
    【解决方案4】:

    260MB 并不是那么大。您应该能够将整个内容加载到内存中,然后对其进行解析。进入后,您可以使用嵌套循环读取行尾之间的整数并使用常用函数进行转换。在您开始之前,我会尝试为您的整数数组预分配足够的内存。

    哦,您可能会发现粗糙的旧 C 风格文件访问函数是此类事情的更快选择。

    【讨论】:

      【解决方案5】:

      我会这样做:

      #include <fstream>
      #include <iostream>
      #include <string>
      
      using namespace std;
      
      int main() {
      
          fstream file;
          string line;
          int intValue;
          int lineCount = 0;
          try {
              file.open("myFile.txt", ios_base::in); // Open to read
              while(getline(file, line)) {
                  lineCount++;
                  try {
                      intValue = stoi(line);
                      // Do something with your value
                      cout << "Value for line " << lineCount << " : " << intValue << endl;
      
                  } catch (const exception& e) {
                      cerr << "Failed to convert line " << lineCount << " to an int : " << e.what() << endl;
                  }
              }
          } catch (const exception& e) {
              cerr << e.what() << endl;
              if (file.is_open()) {
                  file.close();
              }
          }
      
          cout << "Line count : " << lineCount << endl;
      
          system("PAUSE");
      }
      

      【讨论】:

      • 这可能或多或少是他正在做的事情(减去cout)。使用getline 会导致不必要的复制和可能的分配,而while ( file &gt;&gt; intValue )... 可以避免这种情况。\
      【解决方案6】:

      使用 Qt 会非常简单:

      QFile file("h:/1.txt");
      file.open(QIODevice::ReadOnly);
      QDataStream in(&file);
      
      QVector<int> ints;
      ints.reserve(25000000);
      
      while (!in.atEnd()) {
          int integer;
          qint8 line; 
          in >> integer >> line; // read an int into integer, a char into line
          ints.append(integer); // append the integer to the vector
      }
      

      最后,您有ints QVector,您可以轻松排序。行数与向量的大小相同,前提是文件格式正确。

      在我的机器 i7 3770k @4.2 Ghz 上,读取 2500 万个整数并将它们放入向量大约需要 490 毫秒。从常规机械 HDD 而非 SSD 读取。

      将整个文件缓冲到内存中并没有太大帮助,时间降至 420 毫秒。

      【讨论】:

      • 而且这比其他方法更有效,你有什么参考资料? [我会把它留给安德烈来否决你的帖子]
      • @MatsPetersson - 不要生气,更新了一些数字,尽管阅读是细粒度的,但性能还是不错的。缓存到内存并没有显着提高性能...
      • 你有没有将它与例如常规 C++ ifstream 进行比较?
      • @MatsPetersson - 不,我从不费心学习与 Qt 提供的功能重叠的任何标准功能。也许您可以比较两者并报告数字。
      • 这意味着我在我的机器上安装 QT。我怀疑您的机器上确实有标准 C++ 库,所以也许您可以编译我在另一个答案中发布的代码,并将您的 QT 代码添加到那里的集合中?
      【解决方案7】:

      你没有说你是如何阅读价值观的,所以很难 说。不过,实际上只有两个解决方案:`someIStream

      anIntandfscanf( someFd, "%d", &anInt )` 从逻辑上讲,这些 应该具有相似的性能,但实现方式不同;它 可能都值得尝试和衡量。

      要检查的另一件事是您如何存储它们。如果你知道的话 你有大约 2500 万,做一个 reserve 的 3000 万 std::vector 在阅读它们之前可能会有所帮助。它 用 3000 万构建 vector 也可能更便宜 元素,然后在你看到结尾时修剪它,而不是 使用push_back

      最后,你可以考虑写一个immapstreambuf,然后 使用 mmap 输入,并直接从 映射内存。甚至手动迭代它,调用 strtol(但工作量更大);所有的流媒体 解决方案可能最终会调用strtol,或其他 类似,但首先围绕调用做了大量工作。

      编辑:

      FWIW,我在家用机器上做了一些非常快速的测试(相当 最近的 LeNova,运行 Linux),结果让我感到惊讶:

      • 作为参考,我做了一个简单、幼稚的实现,使用 std::cin &gt;&gt; tmpv.push_back( tmp );,没有尝试 优化。在我的系统上,这运行不到 10 秒。

      • 简单的优化,比如在向量上使用reserve, 或最初创建大小为 25000000 的向量,但没有 变化很大——时间仍然超过 9 秒。

      • 使用很简单的mmapstreambuf,时间降到 大约 3 秒——用最简单的循环,没有reserve, 等等。

      • 使用fscanf,时间降至不到 3 秒。一世 怀疑FILE*的Linux实现也使用 mmap(而std::filebuf 没有)。

      • 最后,使用mmapbuffer,迭代两个char*,然后 使用stdtol进行转换,时间降到了不到一秒,

      这些测试完成得非常快(写完不到一个小时 并运行所有这些),并且远非严格(当然, 不要告诉你任何关于其他环境的信息),但是 差异让我感到惊讶。我没想到会有这么大的差异。

      【讨论】:

        【解决方案8】:

        一种可能的解决方案是将大文件分成更小的块。分别对每个块进行排序,然后将所有已排序的块一个接一个地合并。

        编辑: 显然,这是一种行之有效的方法。请参阅http://en.wikipedia.org/wiki/External_sorting 上的“外部合并排序”

        【讨论】:

        • 这几乎肯定会导致程序需要更多的总时间。
        猜你喜欢
        • 2013-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多