动态分配的数组或std :: vector [英] Dynamically allocated arrays or std::vector

查看:148
本文介绍了动态分配的数组或std :: vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,
我试图优化我的C ++代码。我搜索互联网上使用动态分配的C ++数组vs使用std :: vector和一般看到一个建议支持std :: vector,两者之间的性能差异可以忽略不计。例如,在这里 - http://stackoverflow.com/问题/ 381621 / using-arrays-or-stdvectors-in-c-whats-the-performance-gap



然而,我写了一些代码来测试通过数组/向量迭代和为元素赋值的性能,我通常发现使用动态分配的数组几乎是3比我使用的矢量(我没有指定一个尺寸的矢量预先)。我使用g ++ - 4.3.2。



但是我觉得我的测试可能忽略了我不知道的问题,所以我会感谢任何关于这个问题的建议。 / p>

感谢



使用的代码 -

  #include< time.h> 
#include< iostream>
#include< vector>

using namespace std;

int main(){
clock_t start,end;
std :: vector< int> vec(9999999);
std :: vector< int> :: iterator vecIt = vec.begin();
std :: vector< int> :: iterator vecEnd = vec.end();

start = clock();
for(int i = 0; vecIt!= vecEnd; i ++){
*(vecIt ++)= i;
}
end = clock();
cout<<vector:<<(double)(end-start)/ CLOCKS_PER_SEC<< endl;

int * arr = new int [9999999];
start = clock();
for(int i = 0; i <9999999; i ++){
arr [i] = i;
}
end = clock();
cout<<array:<<(double)(end-start)/ CLOCKS_PER_SEC<< endl;
}


解决方案

重要的是启用大多数编译器优化。我自己对SO的几个答案已经犯了错误 - 例如,当类似operator []的内容未内联时的函数调用开销可能非常重要。


Hey, I'm trying to optimize my C++ code. I've searched the internet on using dynamically allocated C++ arrays vs using std::vector and have generally seen a recommendation in favor of std::vector and that the difference in performance between the two is negligible. For instance here - http://stackoverflow.com/questions/381621/using-arrays-or-stdvectors-in-c-whats-the-performance-gap.

However, I wrote some code to test the performance of iterating through an array/vector and assigning values to the elements and I generally found that using dynamically allocated arrays was nearly 3 times faster than using vectors (I did specify a size for the vectors beforehand). I used g++-4.3.2.

However I feel that my test may have ignored issues I don't know about so I would appreciate any advice on this issue.

Thanks

Code used -

#include <time.h>
#include <iostream>
#include <vector>

using namespace std;

int main() {
  clock_t start,end;
  std::vector<int> vec(9999999);
  std::vector<int>::iterator vecIt = vec.begin();
  std::vector<int>::iterator vecEnd = vec.end();

  start = clock();
  for (int i = 0; vecIt != vecEnd; i++) {
    *(vecIt++) = i;
  }
  end = clock();
  cout<<"vector: "<<(double)(end-start)/CLOCKS_PER_SEC<<endl;

  int* arr = new int[9999999];
  start = clock();
  for (int i = 0; i < 9999999; i++) {
    arr[i] = i;
  }
  end = clock();
  cout<<"array: "<<(double)(end-start)/CLOCKS_PER_SEC<<endl;
}

解决方案

When benchmarking C++ comtainers, it's important to enable most compiler optimisations. Several of my own answers on SO have fallen foul of this - for example, the function call overhead when something like operator[] is not inlined can be very significant.

这篇关于动态分配的数组或std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆