【发布时间】:2011-07-25 22:56:11
【问题描述】:
与一位同事讨论的结果是,我最终编写了基准测试来测试 std::vector 与原始动态分配的数组,结果令人惊讶。
我的测试如下:
#include "testconsts.h" // defines NUM_INTS across all tests
#include <vector>
int main()
{
const int numInts = NUM_INTS;
std::vector<int> intVector( numInts );
int * const intArray = new int[ numInts ];
++intVector[0]; // force access to affect optimization
++intArray[0]; // force access to affect optimization
for( int i = 0; i < numInts; ++i )
{
++intArray[i];
}
delete[] intArray;
return 0;
}
和:
#include "testconsts.h" // defines NUM_INTS across all tests
#include <vector>
int main()
{
const int numInts = NUM_INTS;
std::vector<int> intVector( numInts );
int * intArray = new int[ numInts ];
++intArray[0]; // force access to affect optimization
++intVector[0]; // force access to affect optimization
for( int i = 0; i < numInts; ++i )
{
++intVector[i];
}
delete[] intArray;
return 0;
}
它们是用 g++ -O3 和 gcc 4.4.3 编译的
使用time 多次运行基准测试的结果类似于:
数组:
real 0m0.757s
user 0m0.176s
sys 0m0.588s
矢量:
real 0m0.572s
user 0m0.268s
sys 0m0.304s
三件事很清楚:
- 数组在用户时间上更快
- 向量速度更快,系统时间更短
- 在这场战斗中,vector 赢得了所有胜利
问题是“为什么?”。
我猜测系统时间问题一定与页面错误有关,但我无法准确描述为什么会有更多页面错误。
至于用户时间问题,我不太感兴趣,但我仍然很好奇对此的看法。我以为它与初始化有关,尽管我没有将初始化值传递给向量构造函数,所以我不知道。
【问题讨论】:
-
尝试使用其他类型的向量...这可能与针对 32 位整数的向量类的优化有关。他们这样做是为了布尔。
-
@Thomas:这太错误了。向量在内部使用分配的空间用作数组。 vector
是一个完全不同的动物,一个设计错误 -
比较组装怎么样?这应该会给你一个很好的主意。
-
@Catskul:你已经知道答案了:更多的页面错误,你只需要解释为什么会这样,你不需要去汇编,高级 C++ 的解释就足够了:
std::vector默认会在构造时初始化元素,而您的代码中的new不会。数组测试支付两个容器的成本,而向量测试只有自己的成本。
标签: c++ performance stl vector profiling