我正在做一些项目,我想知道哪种方式最有效地从文件中读取大量数据(我说的是 100 行的文件,最多 30 亿行,可以多想想)。读取后,数据将存储在结构化数据集中(vector<entry>
,其中“条目”定义结构化行)。
此文件的结构化行可能如下所示:
string int int int string string
这也以适当的平台结束 EOL
并且是 TAB 分隔的
我希望完成的是:
- 将文件读入内存(
string
)或vector<char>
- 从我的缓冲区中读取原始数据并将其格式化为我的数据集。
我需要考虑内存占用和快速解析速度。
我已经在避免使用 stringstream
因为它们看起来太慢了。
我还避免了对我的文件的多次 I/O 调用:
// open the stream
std::ifstream is(filename);
// determine the file length
is.seekg(0, ios_base::end);
std::size_t size = is.tellg();
is.seekg(0, std::ios_base::beg);
// "out" can be a std::string or vector<char>
out.reserve(size / sizeof (char));
out.resize(size / sizeof (char), 0);
// load the data
is.read((char *) &out[0], size);
// close the file
is.close();
我想过把这个巨大的 std::string
然后逐行循环,我会将行信息(字符串和整数部分)提取到我的数据集行中。有更好的方法吗?
编辑:此应用程序可以在 32 位、64 位计算机或用于更大文件的 super 计算机上运行。
非常欢迎任何建议。
谢谢
最佳答案
一些随机的想法:
- 在开始时使用 vector::resize()(你这样做了)
- 一次读取大块文件数据,至少 4k,最好是 256k。将它们读入内存缓冲区,将该缓冲区解析为您的 vector 。
- 不要一次读取整个文件,这可能会导致不必要的交换。
- sizeof(char) 总是 1 :)
关于c++ - 从文件中解析原始数据的最快最有效的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13673598/