[英]C++ iterator much slower than indexing?
I have a O(N^2)
program and I notice the huge difference between using iterator and index, I paste the code and data here: 我有一个
O(N^2)
程序,我注意到使用迭代器和索引之间的巨大区别,我将代码和数据粘贴到这里:
code: 码:
#include <string>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main(int argc, char* argv[]){
ifstream ifile("csv.csv");
string s;
vector<long> vec_frd;
vector<long> vec_real_frd;
while (getline(ifile, s)){
string s2 = s.substr(0, s.find(','));
vec_frd.push_back(stol(s.substr(0, s.find(','))));
}
long real_frd;
// using iterator
vector<long>::iterator it1, it2;
for (it1=vec_frd.begin(); it1<vec_frd.end(); it1++){
if (*it1 == -1){
vec_real_frd.push_back(-1);
continue;
}
real_frd = *it1;
for (it2=it1; it2<it1+*it1 && it2<vec_frd.end(); it2++){
if (*it2 == -1)
real_frd --;
}
vec_real_frd.push_back(real_frd);
}
// using index
// for (unsigned int i=0; i<vec_frd.size(); i++){
// if (vec_frd[i] == -1){
// vec_real_frd.push_back(-1);
// continue;
// }
// real_frd = vec_frd[i];
// for (unsigned int j=i; j<i+vec_frd[i] && j<vec_frd.size(); j++){
// if (vec_frd[j] == -1)
// real_frd --;
// }
// vec_real_frd.push_back(real_frd);
// }
ifile.close();
return 1;
}
data: https://www.dropbox.com/s/c2c7txhu24xy06r/csv.csv?dl=0 数据: https : //www.dropbox.com/s/c2c7txhu24xy06r/csv.csv?dl = 0
if we use iterator, on my machine it takes almost 30s, if we use index instead, it takes 5s, I am new to C++, is that kind of performance difference normal? 如果使用迭代器,则在我的计算机上将花费近30s,如果使用索引,则将花费5s,这对C ++是我的新手,这种性能差异是否正常? Or am I wrong somewhere?
还是我在某个地方错了?
To answer your question - no, this behavior is most definetly not normal for the optimized code. 要回答您的问题-不,对于优化的代码,此行为绝对不是正常现象。
I could not reproduce it with gcc or MSVC. 我无法使用gcc或MSVC复制它。 Your best bet I think is to carefully check your compiler options.
我认为最好的选择是仔细检查编译器选项。
On a side note, I believe you can speed this task up quite a bit with some algorithm tweaking. 附带一提,我相信您可以通过一些算法调整来大大提高此任务的速度。 Even asymptotically I'm pretty sure you can go from
O(N^2)
to O(N)
by precomputing a couple of counters. 即使渐近,我也很确定您可以通过预先计算几个计数器从
O(N^2)
变为O(N)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.