计算功率的最快方式是“2的功率”数字用? [英] Fastest way of computing the power that a "power of 2" number used?

查看:123
本文介绍了计算功率的最快方式是“2的功率”数字用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最快的方法来找到2的权力,一定数量(即二的幂)使用?



我不是很熟练数学,所以我不知道如何最好地描述它。但是该函数看起来类似于 x = 2 ^ y 其中 y 是输出, x 是输入。这是一个真实的表,它会是什么样子,如果这有助于解释它。

  0 = f(1)
1 = f(2)
2 = f
3 = f(8)
...
8 = f(256)
9 = f(512)
pre>

我做了一个函数,但我担心它不是很有效率(或优雅的)。会有一个更简单和更有效的方式这样做吗?我使用这个来计算纹理的什么区域用于缓冲绘图的完成,所以它为每个绘制对象至少调用一次。这是我到目前为止的功能:

  uint32 getThePowerOfTwo(uint32 value){
for(uint32 n = 0; n <32; ++ n){
if(value< =(1<< n)){
return n;
}
}
return 32; //不应该调用
}


解决方案

基于woolstar的答案 - 我想知道一个查找表的二进制搜索是否会稍快? (and nice look)...

  int getThePowerOfTwo(int value)
{
static const int twos [] =
{
1 <<1,<1,<1,1 <2,1 <3,1 <4,1≤N≤5, ;< 6,1<< 7,
1<<< 8,1< 9,1 | <10,1 | <11,1 | <12,1 < ,1 <14,1 <15,
1 <16,1 <17,1 <18,1 <19,1 <<20,1 < ; 21,1 <22,1 <23,
1 <24,1 <25,1 <26,1 <27,1 <28,1 < ;< 29,1<< 30,1<< 31
};

return lower_bound(begin(twos),end(twos),value) - begin(twos);
}


What would be the quickest way to find the power of 2, that a certain number (that is a power of two) used?

I'm not very skilled at mathematics, so I'm not sure how best to describe it. But the function would look similar to x = 2^y where y is the output, and x is the input. Here's a truth table of what it'd look like if that helps explain it.

0 = f(1)
1 = f(2)
2 = f(4)
3 = f(8)
...
8 = f(256)
9 = f(512)

I've made a function that does this, but I fear it's not very efficient (or elegant for that matter). Would there be a simpler and more efficient way of doing this? I'm using this to compute what area of a texture is used to buffer how drawing is done, so it's called at least once for every drawn object. Here's the function I've made so far:

uint32 getThePowerOfTwo(uint32 value){
    for(uint32 n = 0; n < 32; ++n){
        if(value <= (1 << n)){
            return n;
        }
    }
    return 32; // should never be called
}

解决方案

Building on woolstar's answer - I wonder if a binary search of a lookup table would be slightly faster? (and nicer looking)...

int getThePowerOfTwo(int value)
{
    static const int twos[] = 
    {
        1<<0,  1<<1,  1<<2,  1<<3,  1<<4,  1<<5,  1<<6,  1<<7,
        1<<8,  1<<9,  1<<10, 1<<11, 1<<12, 1<<13, 1<<14, 1<<15,
        1<<16, 1<<17, 1<<18, 1<<19, 1<<20, 1<<21, 1<<22, 1<<23,
        1<<24, 1<<25, 1<<26, 1<<27, 1<<28, 1<<29, 1<<30, 1<<31
    };

    return lower_bound(begin(twos), end(twos), value) - begin(twos);
}

这篇关于计算功率的最快方式是“2的功率”数字用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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