【发布时间】:2018-10-31 10:06:45
【问题描述】:
我已经分析了 c++ 向量和 c 样式数组之间的性能。结果有点出乎意料,因为文献说向量的性能应该非常接近原始数组,但事实并非如此。我在分析中做错了什么吗?
void getVector1(int n)
{
if (n < 0)
{
throw std::invalid_argument(std::string("negative argument n:") + std::to_string(n));
}
auto tp1 = std::chrono::steady_clock::now();
std::vector<int> ivec(n);
int i = 0;
for (auto& x : ivec)
{
x = ++i;
}
auto tp2 = std::chrono::steady_clock::now();
std::chrono::duration<double, std::micro> dd = tp2 - tp1;
printf("spend %6.2f us time to create: %d elements vector inside %s() at %s:%d \n", dd.count(), n, __func__, __FILE__, __LINE__);
}
void getVector2(int n)
{
if (n < 0)
{
throw std::invalid_argument(std::string("negative argument n:") + std::to_string(n));
}
auto tp1 = std::chrono::steady_clock::now();
auto pvec = new int[n];
for (int i = 0; i < n; ++i)
{
pvec[i] = i;
}
auto tp2 = std::chrono::steady_clock::now();
std::chrono::duration<double, std::micro> dd = tp2 - tp1;
delete[] pvec;
printf("spend %6.2f us time to create: %d elements vector inside %s() at %s:%d \n", dd.count(), n, __func__, __FILE__, __LINE__);
}
int main()
{
int n = 10000000;
getVector1(n);
getVector2(n);
return 0;
}
代码是使用带有 -O3 选项的 g++ 编译的。
花费 11946.38 我们的时间来创建:在 testVectorSpeed.cpp 中的 getVector1() 内的 10000000 个元素向量
花费 7298.66 我们的时间来创建:在 testVectorSpeed.cpp 中的 getVector2() 内的 10000000 个元素向量
【问题讨论】:
-
将创建时间与填充它的循环分开可能会有所帮助。
-
我希望一个好的编译器能够意识到你不使用向量或数组,尝试使用它们(在时间之外)。此外,您应该多次运行测量并更改调用顺序
-
@user463035818 堆省略在 gcc 中还没有 AFAIK,所以副作用应该仍然起作用。
-
创建向量时,会调用
memset(),因为整数是默认构造的。如果你改用reserve()和emplace_back(),你可能会得到更好的性能。 -
一个真正的区别是向量中的元素是默认初始化的,但在动态数组中没有太多。试试
vec = new int[n]();
标签: c++ performance vector