Optimizing a floating point division and conversion operation

后端 未结 4 1368
迷失自我
迷失自我 2020-12-19 21:37

I have the following formula

float mean = (r+b+g)/3/255.0f;

I want to speed it up. There are the following preconditions

0         


        
4条回答
  •  清歌不尽
    2020-12-19 22:07

    Pre-convert your divisions into a multiplicable constant:

    a / 3 / 255
    

    is the same as

    a * (1 / (3 * 255))
    

    so pre-compute:

    const float AVERAGE_SCALE_FACTOR = 1.f / (3.f * 255.f)
    

    then just do

    float mean = (r + g + b) * AVERAGE_SCALE_FACTOR;
    

    since multiplying is generally a lot faster than dividing.

提交回复
热议问题