2's complement conversion. Is this right?

Grant Edwards grante at visi.com
Sat Apr 19 05:30:45 CEST 2008


On 2008-04-18, Bob Greschke <bob at passcal.nmt.edu> wrote:

> However, in playing around with your suggestion and Grant's code I've 
> found that the struct stuff is WAY slower than doing something like this
>
>  Value = (ord(Buf[s])*65536)+(ord(Buf[s+1])*256)+ord(Buf[s+2])
>  if Value >= 0x800000:
>      Value -= 0x1000000
>
> This is almost twice as fast just sitting here grinding through a few 
> hundred thousand conversions (like 3sec vs. ~5secs just counting on my 
> fingers - on an old Sun...it's a bit slow).  Replacing *65536 with <<16 
> and *256 with <<8 might even be a little faster, but it's too close to 
> call without really profiling it.

I didn't know speed was important.  This might be a little
faster (depending on hardware):

  Value = (ord(Buf[s])<<16) | (ord(Buf[s+1])<<8) | ord(Buf[s+2])

It also makes the intention a bit more obvious (at least to me).
  
A decent C compiler will recognize that <<16 and <<8 are
special and just move bytes around rather than actually doing
shifts.  I doubt the Python compiler does optimizations like
that, but shifts are still usually faster than multiplies
(though, again, a good compiler will recognize that multiplying
by 65536 is the same as shifting by 16 and just move bytes
around).

-- 
Grant Edwards                   grante             Yow!  If elected, Zippy
                                  at               pledges to each and every
                               visi.com            American a 55-year-old
                                                   houseboy...



More information about the Python-list mailing list