Speedup Bitmap Parser

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Tue Feb 17 19:35:40 CET 2009


Jayson Santos:
> And here is the final code:http://pastebin.com/f3e20d669

Note that if you use Psyco this lookup trick isn't useful, but if the
Psyco isn't available it can improve performance a little:
append = BitmapList['lines'].append


I suggest to replace this code:

        red, green, blue = struct.unpack('BBB', s[i:i+3])
        append({
            'red': red,
            'green': green,
            'blue': blue,
        })

With something just like:

        rbg = struct.unpack('BBB', s[i:i+3])

Later you can access r g and b by their position, avoiding the
allocation and creation of a new dict for each pixel.
(array.array too is able to do that, but using unpack is probably fine
too. Using an array.array you can probably decode many rbg triples in
a single time, and slice it later, this looks faster).


In the following code:

if __name__ == '__main__':
    ...
        ...
        for line in BitmapList['lines']:
            for x, color in enumerate(line):
                ...

note that Psyco is able to compile code only if it's inside functions
or methods, so it may give a bit of improvement if you move such loops
into a function.
I don't know if Psyco is already able to compile enumerate(), if not,
then replacing the enumerate with a manual counter speeds up the code.

I think ShedSkin doesn't have the struct module yet, once someone has
written such standard module, you can probably produce a compiled (C+
+) module with your code that 10-50 times faster than the original
Python code, with no changes in the Python code itself :-)

Bye,
bearophile



More information about the Python-list mailing list