Is try-except slow?

Robert Kern robert.kern at gmail.com
Wed Sep 3 01:56:48 CEST 2008


ssecorp wrote:
> or why does this take so god damn long time?

Several reasons. One of which is that try: except: is slow.

> and if I run into an IndexError it break out of the inner loop right?
> so having range up to 10000000 or 1000 wouldn't matter if biggest
> working x is 800?

try: except: needs to set up a few things before the try: suite is executed. You 
pay this cost regardless of whether the exception fires or not.

> def getPixels(fileName):
>     im = PIL.Image.open(fileName)
>     colors = []
>     for y in range(1, 1000):
>         row = []
>         for x in range(1, 1000):
>             try:
>                 color = im.getpixel((x,y))
>                 row.append(color)
>             except IndexError:
>                 break

Images have a size tuple attached to them. I recommend using that to get the 
upper bounds of the iterations.

>             colors.append(row)
>     return numpy.array(colors)

Or, with reasonably modern versions of PIL and numpy:


In [1]: import Image

In [2]: im = Image.open('lena.png')

In [3]: import numpy

In [4]: numpy.asarray(im)
Out[4]:
array([[[228, 134, 132],
         [228, 134, 132],
         [228, 135, 130],
         ...,
         [244, 151, 136],
         [227, 132, 114],
         [197, 102,  82]],

        [[228, 135, 130],
         [228, 135, 130],
         [228, 135, 130],
         ...,
         [237, 145, 124],
         [219, 127, 102],
         [191, 100,  73]],

        [[227, 134, 129],
         [227, 134, 129],
         [227, 134, 127],
         ...,
         [236, 147, 117],
         [216, 130,  97],
         [192, 106,  71]],

        ...,
        [[ 87,  22,  56],
         [ 89,  24,  58],
         [ 90,  25,  59],
         ...,
         [178,  67,  76],
         [180,  65,  72],
         [179,  62,  70]],

        [[ 87,  22,  56],
         [ 88,  23,  57],
         [ 90,  25,  59],
         ...,
         [183,  68,  75],
         [188,  67,  72],
         [190,  67,  72]],

        [[ 86,  21,  55],
         [ 88,  23,  57],
         [ 90,  25,  59],
         ...,
         [186,  70,  73],
         [193,  70,  73],
         [195,  71,  73]]], dtype=uint8)


-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list