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() 和数组索引快,为什么?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
