c++读取文件太慢

c++ reading file is too slow

本文关键字:文件 读取 c++      更新时间:2023-10-16

我正在尝试读取约36KB,大约需要20秒才能完成此循环:

ifstream input_file;
input_file.open("text.txt");
if( !(input_file.is_open()) )
{
    cout<<"File not found";
    exit(1);
}
std::string line;
stringstream line_stream;   //to use << operator to get words from lines
int lineNum=1;
while( getline(input_file,line) )   //Read file line by line until file ends
{
    line_stream.clear();    //clear stream
    line_stream << line;    //read line
    while(line_stream >> word)  //Read the line word by word until the line ends
    {
        //insert word into a linked list...
    }
    lineNum++;
}
input_file.close();

如有任何帮助,我们将不胜感激。

stringstream::clear()不会清除其中的所有上下文。它只重置错误和EOF标志,请参阅http://en.cppreference.com/w/cpp/io/basic_ios/clear.

结果是line_stream累加了之前的所有行,内部循环将一次又一次地在所有累加行上运行单词。

因此,与你期望的O(n)相比,你花费的总时间大约是O(n^2)

您可以在while循环中定义新的line_stream实例,使其具有全新的空实例,而不是在每行中使用相同的对象。像这样:

fstream input_file;
input_file.open("text.txt");
if( !(input_file.is_open()) )
{
    cout<<"File not found";
    exit(1);
}
std::string line;
int lineNum=1;
while( getline(input_file,line) )   //Read file line by line until file ends
{
    stringstream line_stream;   // new instance, empty line.
    line_stream << line;    //read line
    while(line_stream >> word)  //Read the line word by word until the line ends
    {
        //insert word into a linked list...
    }
    lineNum++;
}
input_file.close();

您可以尝试以下操作:

std::ifstream file("text.txt");
std::string str;
while (std::getline(file, str))
{
    cout << str; //call function to to retrieve words of str in memory not in file 
}

我在11毫秒内运行了你的代码,但上面提到的选项在8毫秒内运行。也许它对你有用。

尝试使用构建标志-O2-O3进行编译。

我惊讶地发现,读取1GB文件的简单for循环需要4.7秒,而另一种更高级别的语言(Dart)只需要3.x秒。

启用此标志后,运行时间降至2.1秒。