How to Read Bytes from a file

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Mar 6 02:59:33 CET 2007


En Fri, 02 Mar 2007 08:22:36 -0300, Bart Ogryczak <B.Ogryczak at gmail.com>  
escribió:

> On Mar 1, 7:36 pm, "gregpin... at gmail.com" <gregpin... at gmail.com>
> wrote:
>> Thanks Bart.  That's perfect.  The other suggestion was to precompute
>> count1 for all possible bytes, I guess that's 0-256, right?
>
> 0-255 actually. It'd be worth it, if accessing dictionary with
> precomputed values would be significantly faster then calculating the
> lambda, which I doubt. I suspect it actually might be slower.

Dictionary access is highly optimized in Python. In fact, using a  
precomputed dictionary is about 12 times faster:

py> import timeit
py> count1 = lambda x:  
(x&1)+(x&2>0)+(x&4>0)+(x&8>0)+(x&16>0)+(x&32>0)+(x&64>0)+
(x&128>0)
py> d256 = dict((i, count1(i)) for i in range(256))
py> timeit.Timer("for x in range(256): w = d256[x]", "from __main__ import  
d256"
).repeat(number=10000)
[0.54261253874445003, 0.54763468541393934, 0.54499943428564279]
py> timeit.Timer("for x in range(256): w = count1(x)", "from __main__  
import cou
nt1").repeat(number=10000)
[6.1867963665773118, 6.1967124313285638, 6.1666287195719178]

-- 
Gabriel Genellina




More information about the Python-list mailing list