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() 和数组索引快,为什么?
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07