Does Python allow access to some of the implementation details?

Claudio Grondi claudio.grondi at freenet.de
Fri Jan 6 13:25:29 CET 2006


Let's consider a test source code given at the very end of this posting.

The question is if Python allows somehow access to the bytes of the 
representation of a long integer or integer in computers memory?
Or does Python hide such implementation details that deep, that there is 
no way to get down to them?

The test code below shows, that extracting bits from an integer value n 
is faster when using n&0x01 than when using n%2 and I suppose it is 
because %2 tries to handle the entire integer, where &0x01 processes 
only the last two bytes of it (I come to this because the speed 
difference between &0x01 and %2 operations depends on how large the 
value n is). If it were possible to 'tell' the %2 operation to operate 
only on one short of the integer number representation there will be 
probably no difference in speed. Is there a way to do this efficiently 
in Python like it is possible in C when using pointers and recasting?

As I am on Python 2.4.2 and Microsoft Windows, I am interested in 
details related to this Python version (to limit the scope of the 
question).

Claudio

Here the code:

import time

# i = 2**25964951 - 1
i = 123456789**123
lstBitsModulo = []
start = time.clock()
while i:
   i=i>>1
   lstBitsModulo.append(i%2)
speedModulo = time.clock()-start

# i = 2**25964951 - 1
i = 123456789**123
lstBitsBitwiseAnd = []
start = time.clock()
while i:
   i=i>>1
   lstBitsBitwiseAnd.append(i&0x01)
speedBitwiseAnd = time.clock()-start

print
if lstBitsBitwiseAnd == lstBitsModulo :
   print 'BitwiseAnd = %f '%(speedBitwiseAnd,)
   print 'Modulo     = %f '%(speedModulo,)

print # both lists are lists of long integer values
print lstBitsBitwiseAnd[0:3]
print lstBitsModulo[0:3]



More information about the Python-list mailing list