What has a better performance: multiplication or division?

后端 未结 4 1870
天涯浪人
天涯浪人 2020-12-18 07:00

Which version is faster ? x * 0.5 or x / 2

Ive had a course at the university called computer systems some time ago. From back then i remember that mult

4条回答
  •  Happy的楠姐
    2020-12-18 07:35

    Usually division is a lot more expensive than multiplication, but a smart compiler will often convert division by a compile-time constant to a multiplication anyway. If your compiler is not smart enough though, or if there are floating point accuracy issues, then you can always do the optimisation explicitly, e.g. change:

     float x = y / 2.5f;
    

    to:

     const float k = 1.0f / 2.5f;
    
     ...
    
     float x = y * k;
    

    Note that this is most likely a case of premature optimisation - you should only do this kind of thing if you have profiled your code and positively identified division as being a performance bottlneck.

提交回复
热议问题