我正在逐行读取文件,并从中提取整数。一些值得注意的点:
- 输入文件不是二进制文件;
- 我无法在内存中加载整个文件;
文件格式(仅整数,由一些分隔符分隔):
x1 x2 x3 x4 ... y1 y2 y3 ... z1 z2 z3 z4 z5 ... ...
只是为了添加上下文,我正在读取整数并计算它们,使用 std::unordered_map<unsigned int, unsinged int>
.
简单地遍历行,并分配无用的字符串流,如下所示:
std::fstream infile(<inpath>, std::ios::in);
while (std::getline(infile, line)) {
std::stringstream ss(line);
}
700MB 的文件大约需要 2.7 秒。
解析每一行:
unsigned int item;
std::fstream infile(<inpath>, std::ios::in);
while (std::getline(infile, line)) {
std::stringstream ss(line);
while (ss >> item);
}
同一文件给我 ~17.8s。
如果我将运算符更改为 std::getline
+ atoi
:
unsigned int item;
std::fstream infile(<inpath>, std::ios::in);
while (std::getline(infile, line)) {
std::stringstream ss(line);
while (std::getline(ss, token, ' ')) item = atoi(token.c_str());
}
它给了 ~14.6 秒。
还有比这些方法更快的方法吗?我不认为有必要加快文件读取速度,只是解析本身——两者都不会造成任何伤害,不过 (:
最佳答案
这个程序
#include <iostream>
int main ()
{
int num;
while (std::cin >> num) ;
}
读取文件大约需要 17 秒。这段代码
#include <iostream>
int main()
{
int lc = 0;
int item = 0;
char buf[2048];
do
{
std::cin.read(buf, sizeof(buf));
int k = std::cin.gcount();
for (int i = 0; i < k; ++i)
{
switch (buf[i])
{
case '\r':
break;
case '\n':
item = 0; lc++;
break;
case ' ':
item = 0;
break;
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
item = 10*item + buf[i] - '0';
break;
default:
std::cerr << "Bad format\n";
}
}
} while (std::cin);
}
同一文件需要 1.25 秒。随心所欲...
关于c++ - 加速从 C++ 文件中读取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15163751/