Does Python allow access to some of the implementation details?

"Martin v. Löwis" martin at v.loewis.de
Sat Jan 7 00:29:58 CET 2006


Claudio Grondi wrote:
> The question is if Python allows somehow access to the bytes of the
> representation of a long integer or integer in computers memory?

Not sure what you mean by "Python", and "allows" here. I allow you :-)

To do so, write a C file that is a Python module, and accesses the
internal representation of the long. Works super-fast.

You can get somewhat faster in Python than your code if you avoid
producing new long objects all the time, and do the task in chunks of 30
bits.

Regards,
Martin

import time

repeats = [None]*100

start = time.clock()
for repeat in repeats:
    i = 123456789**123
    lstBitsBitwiseAnd = []
    while i:
        lstBitsBitwiseAnd.append(i&0x01)
        i=i>>1
print time.clock()-start

start = time.clock()
for repeat in repeats:
    i = 123456789**123
    lstBitsBitwiseAnd = []
    done = False
    while i:
        i1 = int(i & 0x3FFFFFFF)
        i >>= 30
        if i == 0: done = True
        for k in xrange(30):
            lstBitsBitwiseAnd.append(i1 & 1)
            i1 >>= 1
            if done and i1==0:
                # if this is the top word, and no bits are left,
                # we are done
                break
print time.clock()-start



More information about the Python-list mailing list