【发布时间】:2014-03-13 18:25:20
【问题描述】:
我有一个类似的大型 CSV(大约 75 MB):
1,2,4
5,2,0
1,6,3
8,3,1
...
我用这段代码存储我的数据:
#include <sstream>
#include <fstream>
#include <vector>
int main()
{
char c; // to eat the commas
int x, y, z;
std::vector<int> xv, yv, zv;
std::ifstream file("data.csv");
std::string line;
while (std::getline(file, line)) {
std::istringstream ss(line);
ss >> x >> c >> y >> c >> z;
xv.push_back(x);
yv.push_back(y);
zv.push_back(z);
}
return 0;
}
我在这个大的 CSV (~75MB) 中占用了我:
real 0m7.389s
user 0m7.232s
sys 0m0.132s
太多了!
最近,使用 Sublime Text 的 Snippet,我找到了另一种读取文件的方法:
#include <iostream>
#include <vector>
#include <cstdio>
int main()
{
std::vector<char> v;
if (FILE *fp = fopen("data.csv", "r")) {
char buf[1024];
while (size_t len = fread(buf, 1, sizeof(buf), fp))
v.insert(v.end(), buf, buf + len);
fclose(fp);
}
}
我在这个大的 CSV (~75MB) 中花了我(没有获取数据):
real 0m0.118s
user 0m0.036s
sys 0m0.080s
这在时间上是一个巨大的差异!
问题是如何以更快的方式在字符向量中获取 3 个向量中的数据!我不知道我怎样才能以比第一个建议更快的方式做到这一点。
非常感谢! ^^
【问题讨论】:
-
首先这两个程序是不等价的。其次,这两个程序实际上都没有正确解析文件(第二个程序甚至没有尝试获取单独的值)。
-
尝试使用双端队列而不是向量。另外,您对文件有任何控制权吗?
-
我同意 Joachim Pileborg 的观点。您的代码都没有解析 CSV
标签: c++ performance csv serialization