473,718 Members | 2,066 Online

# Slow Python - what can be done?

Hey,

I'm an experience programmer but new to Python. I'm doing a simple
implementation of a field morphing techinique due to Beier and Neely
(1992) and I have the simple case working in Python 2.3 - but it's
REALLY slow.

Basically, you specify two directed line segments in the coordinate
system of a raster image and use the difference between those two
lines to transform the image.

for a 400 x 600 image, python takes about 30 seconds to run the
algorithm. This seems way to slow - I would expect it to run in a
matter of a few seconds. Here's the code: what should I do to speed
things up? I know I'm going to get a "do it in C/make a C extension"
but that defeats the purpose: I'd like to know what Python can do
here.

from Tkinter import *
import Image
import ImageTk
from sys import exit
from math import sqrt

class Point:
# A Point in the plane
def __init__(self, int1, int2):
# Constructor
self.x = float(int1)
self.y = float(int2)
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
# Sub two points
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, other):
# Either mult by a constant or dot product
if type(other) == float or type(other) == int:
return Point(self.x*ot her, self.y*other)
else:
return self.x*other.x + self.y*other.y
def __div__(self,ot her):
# division by a constant
if type(other) == float or type(other) == int:
return Point(self.x/other, self.y/other)
def __rmul__(self, other):
# multiplication by a constant
return Point(self.x*ot her, self.y*other)
def __rdiv__(self, other):
# division by a constant
return Point(other/self.x, other/self.y)
def __str__(self):
# printing represenation
return '(%s, %s)' % (self.x, self.y)
def length(self):
# regular length
return sqrt(pow(self.x , 2) + pow(self.y, 2))
def perpindicular(s elf):
# 90 deg rotation
return Point(self.y, -self.x)
def to_tuple(self):
# makes a tuple of ints
return (int(self.x), int(self.y))
class WarpLine:
# The lines used to warp the image
def __init__(self, x0, y0, x1, y1, id):
# Constructor - just two points - id not used yet.
self.id = 0
self.point1 = Point(x0, y0)
self.point2 = Point(x1, y1)
def __str__(self):
# Printing
return '%s->%s' % (self.point1, self.point2)
def length(self):
# Segment length
return sqrt(pow(self.p oint2.x-self.point1.x, 2) +
pow(self.point2 .y-self.point1.y, 2))
def getUV(self, point):
# v = shortest distance of point to line
# u = the parameterizatio n of the closest point from v
diff = (self.point2 - self.point1)
u = ((point - self.point1) * diff) / (diff * diff)

v = ((point - self.point1) * diff.perpindicu lar()) / sqrt(diff
* diff)

return u, v
def transformPoint( self, line, point):
# finds transform of point based on self and line
diff = (line.point2 - line.point1)
u, v = self.getUV(poin t)
return line.point1 + u * diff + (v * diff.perpindicu lar()) /
sqrt(diff * diff)

class Picture:
# A simple image class
def __init__(self, file):
self.data = Image.open(file )
def in_bounds(self, pt):
# is point in our bounds?
if pt.x < 0 or pt.y < 0 or pt.x > self.data.size[0] - 1 or
pt.y > self.data.size[1] - 1:
return 0
else:
return 1
def warp(self, source, line1, line2):
# Do transformPoint on each pixel, save results
# This is the slow part of the program
dest = list(self.data. getdata())
src = source.data.get data()
for x in range(0, self.data.size[0] - 1):
for y in range(0, self.data.size[1] - 1):
xy = line1.transform Point(line2,
Point(x,y)).to_ tuple()

if self.in_bounds( Point(xy[0], xy[1])):
dest[x + y*self.data.siz e[0]] = src[xy[0] +
xy[1]*self.data.size[0]]

else:
dest[x + y*self.data.siz e[0]] = 0

self.data.putda ta(dest)
def show(self):
# show the image
root = Tk()
canvas = Canvas(root, width=self.data .size[0],
height=self.dat a.size[1])
canvas.pack()
photo = ImageTk.PhotoIm age(self.data)
disp = canvas.create_i mage(0, 0, anchor=NW, image=photo)
mainloop()
Jul 18 '05 #1
16 2586
In article <48************ **************@ posting.google. com>, Jason wrote:
Basically, you specify two directed line segments in the coordinate
system of a raster image and use the difference between those two
lines to transform the image. # This is the slow part of the program
dest = list(self.data. getdata())
src = source.data.get data()
for x in range(0, self.data.size[0] - 1):
for y in range(0, self.data.size[1] - 1):

"For loops" are evil ;-) Though I'm not familiar with your algorithm, you
should investigate the Numeric/numarray package, which is designed to
do lots of number crunching fast. If you can cast your problem into
good Numeric form, you'll see a speedup of a factor of hundreds.

Mike

--
Dr. Michael Ressler
Research Scientist, Astrophysics Research Element, Jet Propulsion Laboratory
Email: re*****@cheetah .jpl.nasa.gov Phone: (818)354-5576
"A bad night at the telescope is still better than the best day at the office."
Jul 18 '05 #2
On 18 Mar 2004 09:43:19 -0800, se******@rocknr oll.umcs.maine. edu
(Jason) wrote:
Hey,

I'm an experience programmer but new to Python. I'm doing a simple
implementati on of a field morphing techinique due to Beier and Neely
(1992) and I have the simple case working in Python 2.3 - but it's
REALLY slow.

My impression is that you should avoid the Point class. It's a pretty
trivial class, but each time it is instantiated or an instance
destroyed you get some overhead. Do that enough times and you get
speed issues. If you can live with tuples and non-member functions,
that may be some help.

Also, for the picture data itself, possibly you should look at the
numarray library. I haven't used it myself, but I suspect that it will
have lower overheads than a standard Python list.

http://www.pfdubois.com/numpy/
You also seem to be doing too much avoidable work in your inner loop.
For instance, you could swap your x and y loops, and calculate things
like y*self.data.siz e[0] once per row (rather than for every single
pixel). I imagine there are also aspects of the transform calculation
that could be done once per row to save time, though I haven't looked
that closely at what you are doing.
--
Steve Horne

steve at ninereeds dot fsnet dot co dot uk
Jul 18 '05 #3
"Jason" <se******@rockn roll.umcs.maine .edu> wrote in message
news:48******** *************** ***@posting.goo gle.com...
Hey,

I'm an experience programmer but new to Python. I'm doing a simple
implementation of a field morphing techinique due to Beier and Neely
(1992) and I have the simple case working in Python 2.3 - but it's
REALLY slow.

<code snipped>

Here's a couple of thoughts:

- Replace the implementation of WarpLine.length () from:
return sqrt(pow(self.p oint2.x-self.point1.x, 2) +
pow(self.point2 .y-self.point1.y, 2))
to
return math.hypot( (self.point2-self.point1).to _tuple() )

If length() is called repeatedly for a given WarpLine, then cache this
value in an instance variable, and reset it if transformPoint is ever
called.

- Fire up the hotshot profiler. It will tell you which functions really
need tuning. Even though you've identified the "slow part", there are
several function calls made from this segment, any of which could be the
real hot spot.

- Look into using psyco. It is *very* non-intrusive, and you may find you
can get some major speed-up. The simplest way to get started, after
import pysco
psyco.full()
psyco can get in the way of hotshot line profiling. But you will still get
accurate counts and timing at a function call level.

- Your Point class does a lot of type checking when multiplying or dividing
by a constant. Is this worth the penalty you are paying every time these
functions get called? Oh, wait, I see that __mul__ may be multiplying by a
constant, or doing a dot product. If hotshot tells you this is a choke
point, you might rethink using this one method for both functions. Or at
least, reduce your type() calls by changing from:
if type(other) == float or type(other) == int:
return Point(self.x*ot her, self.y*other)
else:
return self.x*other.x + self.y*other.y
to:
if isinstance(othe r, Point):
return self.x*other.x + self.y*other.y
else:
return Point(self.x*ot her, self.y*other)

- If you are forced to comparing types instead of using isinstance, I think
'is' would be a bit better than '=='.

- Why does Point.to_tuple( ) return int's, although you use floats
throughout? Since it looks like you have set up Point to be immutable, can
you keep both a float and an int member value for x and y, so you don't have
to do extra conversions? Also, since WarpLine also appears to be immutable,
you should be able to cache diff and diff*diff (maybe call it diff2 or
diffSquared) - either initialize in the __init__ method, or compute lazily
when needed.

- Experience in other languages sometimes gets in your way when using
Python. Not sure if this has any performance impact, but
Picture.in_boun ds() can be made more Pythonic, as (also, double check use of
'<' vs '<='):

def in_bounds(self, pt):
return (0 <= pt.x <= self.data.size[0] and 0 <= pt.y <=
self.data.size[1])

- Another thing to get used to in Python that is unlike other languages is
the return of ordered pairs of values. Look at this code:
xy = line1.transform Point(line2, Point(x,y)).to_ tuple()

if self.in_bounds( Point(xy[0], xy[1])):
dest[x + y*self.data.siz e[0]] = src[xy[0] +
xy[1]*self.data.size[0]]
else:
dest[x + y*self.data.siz e[0]] = 0

You return a tuple, lets call it (transx, transy), representing the
transformed point, then create a new Point using the separate elements to
test for in_bounds-ness, and then access the individual pieces using [0] and
[1] accesses. Function calls are performance killers in Python, so avoid
them where possible. Try this instead:
transPt = line1.transform Point(line2, Point(x,y))
transx, transy = transPt.to_tupl e() # or even transx,
transy = transPt.x, transPt.y

if self.in_bounds( transPt):
dest[x + y*self.data.siz e[0]] = src[transx +
transy*self.dat a.size[0]]
else:
dest[x + y*self.data.siz e[0]] = 0

- You also reference self.data.size[0] *many* times, even though this is
invariant across all your nested loops. Store this in a local variable
before you start your outer for loop, call it something like "xsize". Then
replace every use of "self.data. size[0]" with "xsize". As an added bonus,

- Your arithmetic operators can generate *lots* of temporary Point objects.
You can streamline some of this process by defining a __slots__ attribute at
the class level, listing the field names "x" and "y". This will keep Python
from allocating a dictionary for all possible attribute names and values for
every Point object created. Likewise for WarpLine.

HTH,
-- Paul
Jul 18 '05 #4
On Thu, 18 Mar 2004 09:43:19 -0800, Jason wrote:
Hey,

I'm an experience programmer but new to Python. I'm doing a simple
implementation of a field morphing techinique due to Beier and Neely
(1992) and I have the simple case working in Python 2.3 - but it's
REALLY slow.

Basically, you specify two directed line segments in the coordinate
system of a raster image and use the difference between those two
lines to transform the image.

for a 400 x 600 image, python takes about 30 seconds to run the
algorithm. This seems way to slow - I would expect it to run in a
matter of a few seconds. Here's the code: what should I do to speed
things up? I know I'm going to get a "do it in C/make a C extension"
but that defeats the purpose: I'd like to know what Python can do
here.

[SNIP]

I can't try your prog because I have not Tkinter,
but I think this app would gain a lot in performances using psyco.
http://psyco.sourceforge.net/ <-- home
http://psyco.sourceforge.net/psycoguide/index.html <-- doc

The simplest way to use psyco is putting
import psyco
psyco.full()

Ciao,
Riccardo
--
-=Riccardo Galli=-

_,e.
s~ ``
~@. ideralis Programs
.. ol
`**~ http://www.sideralis.net
Jul 18 '05 #5

Jason> Here's the code: what should I do to speed things up?

Without considering your code, two suggestions come to mind. One, look at
PIL or Numeric. Perhaps one of them has a more efficient C-based Image
class or array class will will help. Two, if you're running on an Intel
Pentium-type processor (Windows or Linux), take a look at psyco.

http://www.pythonware.com/products/pil/
http://psyco.sourceforge.net/

If you don't have Intel hardware, you might consider PyInline or SciPy's
weave tool to easily inline bits of C code into your Python.

A quick look at your code suggests that you use a fair amount of abstraction
(nothing wrong with that), then throw it away:

xy = line1.transform Point(line2, Point(x,y)).to_ tuple()
if self.in_bounds( Point(xy[0], xy[1])):
...

In the above, you instantiate a Point using x and y, then pass it to
transformPoint( ) which returns new Point. You immediately discard that
point by calling .to_tuple(), then in the next statement create yet another
Point with those same coordinates. Why not just have transformPoint accept
a tuple and return a tuple or at least save the transformed Point for later
use?

Skip

Jul 18 '05 #6
Hello Jason,
I'm an experience programmer but new to Python. I'm doing a simple
implementation of a field morphing techinique due to Beier and Neely
(1992) and I have the simple case working in Python 2.3 - but it's
REALLY slow. Did you use hotshot to find *where* you spend the time?
class Point:
...

I've found out the Python's faster with native types.
One thing is to use a tuple for the point and have functions like
point_sub(p1, p2)

You can try and use Psyco, in several cases it gives a very big speedup.

HTH.
Miki
Jul 18 '05 #7
Thanks for the help - I wasn't aware of the profilers avilable for
Python.

My uber-abstraction is due to recently fleeing from C (abstraction
made hard) and Lisp (no workable GUI stuff) so I'm stuck in the
middle. Anyway, I appreciate the comments.

Jason
Jul 18 '05 #8
se******@rocknr oll.umcs.maine. edu (Jason) wrote in message news:<48******* *************** ****@posting.go ogle.com>...
Hey,

I'm an experience programmer but new to Python. I'm doing a simple
implementation of a field morphing techinique due to Beier and Neely
(1992) and I have the simple case working in Python 2.3 - but it's
REALLY slow.

Basically, you specify two directed line segments in the coordinate
system of a raster image and use the difference between those two
lines to transform the image.

for a 400 x 600 image, python takes about 30 seconds to run the
algorithm. This seems way to slow - I would expect it to run in a
matter of a few seconds. Here's the code: what should I do to speed
things up? I know I'm going to get a "do it in C/make a C extension"
but that defeats the purpose: I'd like to know what Python can do
here.

If you can't go with the mentioned compilers (psycho) or libraries
there is nothing else then writing C. Python is best at glueing code
together. Writing numerical or highly mathematical algorithms in
python will always result in 10000% overhead.

Maybe you want to look at GNU eiffel (smarteiffel).

Remember there is no silver bullet !
Jul 18 '05 #9
se******@rocknr oll.umcs.maine. edu (Jason) writes:
Thanks for the help - I wasn't aware of the profilers avilable for
Python.

You might abuse complex numbers for points (the lisp faq recommends
doing this), maybe it speeds things up. You might even save time (I
did not try this, but hardware operations might be cheaper than Python
procedure calls) by doing complex products and ignoring the imaginary
part of the result just to get quickly at stuff like
p1.x*p2.x-p1.y*p2.y.

If you come from the lisp world anyway, you might try STk or stklos
(schemes with OO and Tk (or GTK) bindings).

Ralf
--
GS d->? s:++>+++ a+ C++++ UL+++ UH++ P++ L++ E+++ W- N++ o-- K- w--- !O M- V-
PS+>++ PE Y+>++ PGP+ !t !5 !X !R !tv b+++ DI+++ D? G+ e++++ h+ r? y?
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.