Is try-except slow?

John Machin sjmachin at lexicon.net
Tue Sep 2 20:36:07 EDT 2008


On Sep 3, 9:44 am, ssecorp <circularf... at gmail.com> wrote:
> or why does this take so god damn long time?

Because your code does so many god damn unnecessary things. Apart from
the fact (as pointed out already by Robert) that you are needlessly
finding the sizes (Y, X) that are already available:

(1) You are executing a try block Y*X (approx) times instead of the Y+X
+2 times it would take if you were to do preliminary probes to find Y
and X
(2) You are doing range(1, 1000) Y times instead of once [see question
below]
(3) You are doing the method lookup im.getpixel Y*X times instead of
once
(4) you are doing the method lookup row.append Y*X times instead of Y
times

> 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?
>
> def getPixels(fileName):
>     im = PIL.Image.open(fileName)
>     colors = []
>     for y in range(1, 1000):

Are you sure that both occurrences of range(1, 1000) shouldn't be
range(1000)?

>         row = []
>         for x in range(1, 1000):
>             try:
>                 color = im.getpixel((x,y))
>                 row.append(color)
>             except IndexError:
>                 break
>             colors.append(row)
>     return numpy.array(colors)

and it appears that you haven't bothered to read the manual section on
Image.getpixel:
"""
Note that this method is rather slow; if you need to process larger
parts of an image from Python, you can either use pixel access objects
(see load), or the getdata method.
"""




More information about the Python-list mailing list