std::vector reserve() and push_back() is faster than resize() and array index, why?(std::vector Reserve() 和 push_back() 比 resize() 和数组索引快,为什么?)
问题描述
我正在对一段代码进行快速性能测试
I was doing a quick performance test on a block of code
void ConvertToFloat( const std::vector< short >& audioBlock,
std::vector< float >& out )
{
const float rcpShortMax = 1.0f / (float)SHRT_MAX;
out.resize( audioBlock.size() );
for( size_t i = 0; i < audioBlock.size(); i++ )
{
out[i] = (float)audioBlock[i] * rcpShortMax;
}
}
我对处理 65536 个音频样本只需要 1 毫秒多一点的原始非常幼稚的实现的速度感到满意.
I was happy with the speed up over the original very naive implementation it takes just over 1 msec to process 65536 audio samples.
不过为了好玩,我尝试了以下方法
However just for fun I tried the following
void ConvertToFloat( const std::vector< short >& audioBlock,
std::vector< float >& out )
{
const float rcpShortMax = 1.0f / (float)SHRT_MAX;
out.reserve( audioBlock.size() );
for( size_t i = 0; i < audioBlock.size(); i++ )
{
out.push_back( (float)audioBlock[i] * rcpShortMax );
}
}
现在我完全期望这能提供与原始代码完全相同的性能.然而,突然之间,循环现在占用了 900 微秒(即它比其他实现快 100 微秒).
Now I fully expected this to give exactly the same performance as the original code. However suddenly the loop is now taking 900usec (i.e. it's 100usec faster than the other implementation).
谁能解释为什么这会提供更好的性能?resize() 是否初始化新分配的向量,而reserve 只是分配但不构造?这是我唯一能想到的.
Can anyone explain why this would give better performance? Does resize() initialize the newly allocated vector where reserve just allocates but does not construct? This is the only thing I can think of.
PS 这是在单核 2Ghz AMD Turion 64 ML-37 上测试的.
PS this was tested on a single core 2Ghz AMD Turion 64 ML-37.
推荐答案
resize 是否初始化新分配的向量,而reserve 只分配但不构造?
Does resize initialize the newly allocated vector where reserve just allocates but does not construct?
是的.
这篇关于std::vector Reserve() 和 push_back() 比 resize() 和数组索引快,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::vector Reserve() 和 push_back() 比 resize() 和数组索引快,为什么?
基础教程推荐
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- c++ STL设置差异 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
