繁体   English   中英

大输入文本文件,每行两个数字,如何更快地输入?

[英]Large Input text file with two numbers each line, how to take input faster?

我有一个格式如下的文本文件-

1 2

3 4

5 6

直到5百万行为止。我正在使用此代码输入-

ifstream fin;
fin.open("abc.txt");
while(!fin.eof()){
    fin>>vert>>adj;
    cout<<vert << "  "<<adj;

}

该程序大约需要15分钟来处理输入。 有什么办法可以加快处理速度。

您最有可能使用调试版本或标准库的非常差的实现。 注意:

  1. 写入文件通常比写入cout更快。
  2. 使用std::endl强制刷新文件,因此非常慢。 不要这样做,而是输出换行符'\\n'
  3. while(! fin.eof())错误的 绝对不要那样做。

这是我的结果:

Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)

t1=3.00009s
t2=10.9166s
t3=18.1806s

测试用例:

// https://github.com/KubaO/stackoverflown/tree/master/questions/ios-timing-40304260
#include <fstream>
#include <iostream>
#include <chrono>
using namespace std;

int main() {
   const int N = 5000000;
   const char kFile1[] = "tmp1.txt", kFile2[] = "tmp2.txt";

   auto start = chrono::system_clock::now();
   {
      ofstream fOut;
      fOut.open(kFile1);
      for (int i = 0; i < N; ++i)
         // !! DO NOT use endl here!
         fOut << i-N << ' ' << N-i << '\n';
   }
   auto t1 = chrono::system_clock::now();
   cerr << "t1=" << chrono::duration<double>(t1-start).count() << "s" << endl;

   double vert, adj;

   {
      ifstream fIn;
      ofstream fOut;
      fIn.open(kFile1);
      fOut.open(kFile2);
      while (fIn >> vert && fIn >> adj)
         // !! DO NOT use endl here!
         fOut << vert << ' ' << adj << '\n';
   }
   auto t2 = chrono::system_clock::now();
   cerr << "t2=" << chrono::duration<double>(t2-t1).count() << "s" << endl;

   {
      ifstream fIn;
      fIn.open(kFile1);
      while (fIn >> vert && fIn >> adj)
         // !! DO NOT use endl here!
         cout << vert << ' ' << adj << '\n';
   }
   auto t3 = chrono::system_clock::now();
   cerr << "t3=" << chrono::duration<double>(t3-t2).count() << "s" << endl;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM