Division and right shift in python

Cevahir Demirkıran cevomed at gmail.com
Wed Aug 26 07:53:01 EDT 2009


Thanks for the answer.
Run it with a big number:
f2(9230821908403878236537264867326482638462035732098490238409328947638257462745672354627356427356742563256745362772537532756732673275732,9)

I had this result:

8.1015883211e-06
1.06158743591e-05
512

2009/8/26 Mark Tolonen <metolone+gmane at gmail.com<metolone%2Bgmane at gmail.com>
>

>
> "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.
>
> -Mark
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Cevahir Demirkiran
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090826/0f073601/attachment.html>


More information about the Python-list mailing list