gpt4 book ai didi

c++ - std::vector 与 std::array 性能对比

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:15:18 27 4
gpt4 key购买 nike

我正在查看新的计时库 (C++11) 并尝试使用它。我写了以下两个程序:

vector .cpp

#include <iostream>
#include <vector>
#include <chrono>

int main()
{
std::vector<double> vector(1000000, 0.);

auto start = std::chrono::high_resolution_clock::now();
for(int i(0); i < vector.size(); i++)
{
vector[i] += 1.;
}
auto end = std::chrono::high_resolution_clock::now();

std::cout << "Elapsed time: " << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << " milliseconds" << std::endl;

return 0;
}

数组.cpp

#include <iostream>
#include <array>
#include <algorithm>
#include <chrono>

int main()
{
std::array<double, 1000000> array;

std::fill(array.begin(), array.end(), 0.);

auto start = std::chrono::high_resolution_clock::now();
for(int i(0); i < array.size(); i++)
{
array[i] += 1.;
}
auto end = std::chrono::high_resolution_clock::now();

std::cout << "Elapsed time: " << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << " milliseconds" << std::endl;

return 0;
}

我得到数组程序为 9 毫秒, vector 程序为 12 毫秒。 std::vector 似乎比 std::array 慢 33%。我做得对吗?为什么会有这种差异?

Ps: 我使用的是 GCC 4.7,Mac OS X 10.7。

g++-mp-4.7 -std=c++11 vector.cpp -o vector
g++-mp-4.7 -std=c++11 array.cpp -o array

最佳答案

我将您的代码更改为:

std::array<double, 1000000> array;

double total = 0;
std::fill(array.begin(), array.end(), 0.);

for (unsigned j = 0; j < 1000; ++j)
{
auto start = std::chrono::high_resolution_clock::now();

for (unsigned i = 0; i < array.size(); i++)
{
array[i] += 1.;
}

auto end = std::chrono::high_resolution_clock::now();
total = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
}

std::cout << total << " for Array." << std::endl;

std::vector<double> vector(1000000, 0.);
total = 0;

for (unsigned j = 0; j < 1000; ++j)
{
auto start = std::chrono::high_resolution_clock::now();

for (unsigned i = 0; i < vector.size(); i++)
{
vector[i] += 1.;
}

auto end = std::chrono::high_resolution_clock::now();
total = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
}

std::cout << total << " for Vector." << std::endl;

我使用 -O3 的结果:

8123 for Array.
8117 for Vector.

在我看来,两者都同样快。

关于c++ - std::vector 与 std::array 性能对比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12121043/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com