std::vector vs std::array 性能

编程入门 行业动态 更新时间:2024-10-11 23:22:38
本文介绍了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 性能

本文发布于:2023-11-05 18:22:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561537.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:性能   std   vector   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!