【发布时间】:2009-07-02 12:28:51
【问题描述】:
我正在尝试优化我的 C++ 代码。我在互联网上搜索了使用动态分配的 C++ 数组与使用 std::vector 的对比,并且通常看到有利于 std::vector 的建议,并且两者之间的性能差异可以忽略不计。例如这里 - Using arrays or std::vectors in C++, what's the performance gap?。
但是,我编写了一些代码来测试遍历数组/向量并将值分配给元素的性能,我通常发现使用动态分配的数组比使用向量快近 3 倍(我确实为事先的向量)。我用的是g++-4.3.2。
但是我觉得我的测试可能忽略了我不知道的问题,所以我很感激关于这个问题的任何建议。
谢谢
使用的代码 -
#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;
}
【问题讨论】:
-
是的,让我们看看你的基准代码。通常,STL 容器的性能问题是由于使用造成的。
-
并确保在关闭调试和优化的情况下编译基准
-
我刚刚运行了您的测试代码并得到:$ ./array vector: 0.021851 array: 0.059796 所以我看到矢量版本更快!
-
编译时优化未开启。 std::vector 现在更快了。感谢您的帮助。
-
@Neil,我认为您的评论应该是公认的答案。也许你应该把它作为一个答案,这样我们就可以投票给它,Sid 可以接受它。 8v)
标签: c++ performance optimization stl