Division and right shift in python

Chris Rebert clp2 at rebertia.com
Wed Aug 26 05:51:30 CEST 2009

```On Tue, Aug 25, 2009 at 8:40 PM, Mark Tolonen<metolone+gmane at gmail.com> wrote:
>
> "Cevahir Demirkiran" <cevomed at gmail.com> wrote in message
> news:3f74e020908251648k7b391a09g78b155507b2f23c4 at mail.gmail.com...
>>
>> Hi,
>>
>> I would like to do a floor division by a power of 2 in python to make it
>> faster than / (modular division in 2.x).
>> However, it is slower.
>> What is the reason of that?
>> I checked them via:
>>
>> def f2(x,n):
>>   t1 = clock()
>>   r = x/pow(2,n)
>>   t2 = clock()
>>   print (t2-t1)
>>   print r
>>   t2 = clock()
>>   r = x>>n
>>   t3 = clock()
>>   print (t3-t2)
>>   print r
>>
>
> It's not slower on my system, but note the inconsistent results also:
>
>>>> f2(1024,5)
>
> 3.47396033483e-06
> 32
> 2.19077375482e-06
> 32
>>>>
>>>> f2(1024,5)
>
> 4.84135603429e-06
> 32
> 3.08499440393e-06
> 32
>>>>
>>>> f2(1024,5)
>
> 4.6782844052e-06
> 32
> 3.77604384028e-06
> 32
>
> Time it with timeit...
>
> C:\>python -m timeit -n 10000000 -s x=1024 "x>>5"
> 10000000 loops, best of 3: 0.113 usec per loop
>
> C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)"
> 10000000 loops, best of 3: 0.468 usec per loop
>
> Right-shift is over 4x faster.

Adjusting for not having to lookup the name "pow", right shift is
still faster, but only slightly.

chris at morpheus ~ \$ python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)"
10000000 loops, best of 3: 0.318 usec per loop
chris at morpheus ~ \$ python -m timeit -n 10000000 -s x=1024 "x/(2**5)"
10000000 loops, best of 3: 0.0973 usec per loop
chris at morpheus ~ \$ python -m timeit -n 10000000 -s x=1024 "x>>5"
10000000 loops, best of 3: 0.0885 usec per loop

Cheers,
Chris
--
http://blog.rebertia.com

```

More information about the Python-list mailing list