std :: vector reserve()和push_back()比resize()和数组索引更快,为什么? [英] std::vector reserve() and push_back() is faster than resize() and array index, why?

查看:782
本文介绍了std :: vector reserve()和push_back()比resize()和数组索引更快,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对一段代码进行了快速性能测试。

  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 {
out [i] =(float)audioBlock [i] * rcpShortMax;
}
}



但是只是为了好玩,我试过下面的

  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 {
out.push_back((float)audioBlock [i] * rcpShortMax);
}
}

现在我完全期望这样做,作为原始代码。然而突然,循环现在需要900usec(即它比其他实现更快100usec)。



任何人都可以解释为什么这会提供更好的性能? resize()初始化新分配的向量,保留只是分配但不构造?这是我能想到的唯一的东西。



PS这是在单核2Ghz AMD Turion 64 ML-37上测试。


<调整大小初始化新分配的向量,保留只是分配但不构造?




是的。


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;
    }
}

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 );
    }
}

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).

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 this was tested on a single core 2Ghz AMD Turion 64 ML-37.

解决方案

Does resize initialize the newly allocated vector where reserve just allocates but does not construct?

Yes.

这篇关于std :: vector reserve()和push_back()比resize()和数组索引更快,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆