Which is better option to use for dividing an integer number by 2?

前端 未结 23 1737
甜味超标
甜味超标 2020-11-27 09:10

Which of the following techniques is the best option for dividing an integer by 2 and why?

Technique 1:

x = x >> 1;

Technique

23条回答
  •  死守一世寂寞
    2020-11-27 09:32

    Obviously, if you are writing your code for the next guy who reads it, go for the clarity of "x/2".

    However, if speed is your goal, try it both ways and time the results. A few months ago I worked on a bitmap convolution routine which involved stepping through an array of integers and dividing each element by 2. I did all kinds of things to optimize it including the old trick of substituting "x>>1" for "x/2".

    When I actually timed both ways I discovered to my surprise that x/2 was faster than x>>1

    This was using Microsoft VS2008 C++ with the default optimizations turned on.

提交回复
热议问题