我的combinedata.csv文件有11230909行,文件大小约为1.6 My。当我尝试将其加载并构造向量字符串到C++中时,这需要超过5个小时。
我的代码不是最优的,也不是高效的。如何将时间减少到尽可能多。知道导入1.6 to的文件和创建变量需要多少优化代码吗?
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<sstream>
#include<vector>
#include<ctime>
using namespace std;
vector <string> data;
vector <string> readcsvfile()
{
string line, val;
ifstream file("combinedata.csv");
while (!file.eof())
{
getline(file, line);
if (!file.good())
break;
stringstream newline(line);
newline << line + ",\n";
if (!newline.good())
break;
while (getline(newline, val, ','))
{
if (val != "NA")
data.push_back(val);
else
break;
}
}
return data;
}
void main()
{
vector <string> data;
data = readcsvfile();
cout << data.size();
cin.get();
}发布于 2015-03-31 20:06:33
是我的代码,不是最优的,也不是高效的。
事实并非如此。std::vector和std::string机会主义地分配内存,这意味着当您填充向量时,您将获得大量的重新分配(一个比下一个大)。
我假设这就是您尝试使用的C和C++代码之间的主要区别:在C中,您没有针对不同用例优化的奇特结构(即与读取1.6 Gb文件不同)。
如何将时间减少到尽可能多。知道导入1.6 to的文件和创建变量需要多少优化代码吗?
不知道“需要多少优化代码”:
为了减少处理时间,尝试不同的算法来读取数据,并测量效率;我将尝试两件事:
发布于 2015-03-31 19:47:53
没有答案,但我现在把它放在这里,因为它不会在评论中出现:
This...
while(!file.eof())
{
getline(file, line);
if(!file.good())
break;
// ...
}...can可以像这样更简单地完成:
while(getline(file, line))
{
// ...
}发布于 2015-03-31 19:50:02
你的代码不是最优的,但我不认为这是你的问题,我认为更多的是你的文件大小的问题。但是,如果你想做更好的代码,你可以:
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void main(){
vector<string> data;
copy_if(istream_iterator<string>(ifstream("combinedata.csv")),
istream_iterator<string>(),
back_inserter(data),
[](const string& i){return i != "NA";});
}正如utnapistim指出的那样,这不能在gcc 5.0之前的版本中工作,因为有一个bug with moving streams。这似乎不是你的问题,因为你使用的是只有Visual Studio支持的void main。但是对于任何在5.0版本之前使用gcc的人,您可以通过将main的主体替换为:
vector<string> data;
ifstream file("combinedata.csv");
copy_if(istream_iterator<string>(file),
istream_iterator<string>(),
back_inserter(data),
[](const string& i){return i != "NA";});https://stackoverflow.com/questions/29367575
复制相似问题