Is & faster than % when checking for odd numbers?

前端 未结 8 949
鱼传尺愫
鱼传尺愫 2020-11-30 04:13

To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?

>>> def isodd(num):
        return num & 1 a         


        
8条回答
  •  醉话见心
    2020-11-30 04:24

    Was really surprised none of the above answers did both variable setup (timing literal is different story) and no function invocation (which obviously hides "lower terms"). Stuck on that timing from ipython's timeit, where I got clear winner x&1 - better for ~18% using python2.6 (~12% using python3.1).

    On my very old machine:

    $ python -mtimeit -s 'x = 777' 'x&1'
    10000000 loops, best of 3: 0.18 usec per loop
    $ python -mtimeit -s 'x = 777' 'x%2'
    1000000 loops, best of 3: 0.219 usec per loop
    
    $ python3 -mtimeit -s 'x = 777' 'x&1'
    1000000 loops, best of 3: 0.282 usec per loop
    $ python3 -mtimeit -s 'x = 777' 'x%2'
    1000000 loops, best of 3: 0.323 usec per loop
    

提交回复
热议问题