本文介绍了std::vector vs std::array 性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在查看新的 chrono 库 (C++11) 并尝试使用它.我写了以下两个程序:
I was looking at the new chrono library (C++11) and trying to use it. I wrote the two following programs:
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; }array.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 毫秒,为向量程序获得了 12 毫秒.std::vector 似乎比 std::array 慢 33%.我做得对吗?为什么会有这种差异?
I obtained 9 millisecond for the array program and 12 milliseconds for the vector program. The std::vector seems about 33% slower than the std::array. I'm doing it right? Why this difference?
Ps:我使用 GCC 4.7,Mac OS X 10.7.
Ps: I'm using 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 推荐答案我把你的代码改成这样:
I changed your code to this:
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.在我看来两者都一样快.
Seems to me that both are equally fast.
更多推荐
std::vector vs std::array 性能
发布评论