Bitshifts and "And" vs Floor-division and Modular

Dave Angel d at davea.name
Thu Sep 6 21:36:54 EDT 2012


On 09/06/2012 08:01 PM, jimbo1qaz wrote:
> Is it faster to use bitshifts or floor division?
Yes, and yes.  Without doing any measurement, I'd expect that in
CPython, it makes negligible performance difference for ordinary ints
(under 2**31, more or less).  Ordinary ints can be done with single
instructions, and any such instruction would be a tiny fraction of the
opcode overhead.

One place were there might be a difference would be for longs.  The
implementation of those would have to be a loop, and eventually one
might be faster than the other.  At that point, maybe you'd want to measure.

>  And which is better, & or %?
> All divisors and mods are power of 2, so are binary operations faster? And are they considered bad style?

The better way is not the faster one, but rather is the one that more
clearly expresses the original problem.  If the problem is a modulo one,
use % (or frequently  divmod).  If the problem is a bit shift/masking
one, then use such operators.

BTW, '/'  on integers is redefined for Python 3.x to give float results,
and not to truncate.

-- 

DaveA




More information about the Python-list mailing list