在C++中从 CSV 获取数据的最快方法
Fastest way to get data from a CSV in C++
>我有一个这样的大型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片段,我找到了另一种读取文件的方法:
#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 个向量中的数据!我不知道我怎样才能以比第一个提议更快的方式做。
谢谢!^^
当然,您的第二个版本会快得多 - 它只是将文件读入内存,而不解析其中的值。与使用 C 样式 I/O 的第一个版本等效的公式如下:
if (FILE *fp = fopen("data.csv", "r")) {
while (fscanf(fp, "%d,%d,%d", &x, &y, &z) == 3) {
xv.push_back(x);
yv.push_back(y);
zv.push_back(z);
}
fclose(fp);
}
对我来说,这比C++式版本快三倍。但是没有中间stringstream
的C++版本
while (file >> x >> c >> y >> c >> z) {
xv.push_back(x);
yv.push_back(y);
zv.push_back(z);
}
几乎一样快。
保存在文件中,里面写了多少个数字。然后,在加载时调整矢量的大小。它可以减少一点时间。
相关文章:
- 通过JNI传递数据数组的最快方法是什么
- 如何使用curlpp通过POST方法上传文件和json数据
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 将线程中的数据存储到全局容器的最佳方法?
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- 在C++中查找像素 RGB 数据的最快方法是什么?
- 构造智能点数据类型以及普通数据类型的通用方法
- 将传入的网络"char*"数据转换为"uint8_t"并返回的安全方法是什么?
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- 在 c++ 中解析数据包数据的最佳方法是什么?
- 处理编译器关于可能丢失数据的警告的最优雅方法是什么
- 创建异构顶点数据数组的可移植方法
- 使用 memcpy 将矢量数据复制到 wstring 的正确方法
- 在 std::vector<无符号字符中存储任意数据的方法>
- 在C++事务之间存储大量字符数据的有效方法
- 学习数据结构和算法的简单方法
- C++中的多维数据集:从 std::vector 的 2D 数据到 std::vector 的 2D 网格的最干净方法?
- C++ 使用派生类方法更改基类数据成员
- 类方法 - 数据结构中 For 循环的运行时错误