c++读取文件太慢
c++ reading file is too slow
我正在尝试读取约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秒。
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量