Pages

Sunday, April 5, 2009

How Fast Is Python For Numerical Computing?

How fast is python for numerical computing? Answer: Pure Python is very slow, python with the NumPY numerical libraries is almost identical to Matlab, and Python where you have weaved C/C++ into your code is nearly as fast as pure C/C++, especially if you use the fast inline algorithm. (Notice you can also work in Fortran with your code.) Here are some benchmarks:

Type of solution Time taken (sec)
Python: 1500.0
Python + NumPy: 29.3
Inline Weave: 4.3
Fast Inline: 2.3
Python/Fortran: 2.9
Matlab: 29.0
Pure C++: 2.16

Just to see what weave looks like, here is an example. As you can see, you can take advantage of all the perks of python and still keep your code fast by converting the slow parts into C/C++ directly in your Python code. See Scipy for more information.:
from scipy.weave import converters
# ...
def inlineTimeStep(self, dt=0.0):
"""Takes a time step using inlined C code -- this version uses
blitz arrays."""
g = self.grid
nx, ny = g.u.shape
dx2, dy2 = g.dx**2, g.dy**2
dnr_inv = 0.5/(dx2 + dy2)
u = g.u

code = """
#line 120 "laplace.py" (This is only useful for debugging)
double tmp, err, diff;
err = 0.0;
for (int i=1; i
for (int j=1; j
tmp = u(i,j);
u(i,j) = ((u(i-1,j) + u(i+1,j))*dy2 +
(u(i,j-1) + u(i,j+1))*dx2)*dnr_inv;
diff = u(i,j) - tmp;
err += diff*diff;
}
}
return_val = sqrt(err);
"""
# compiler keyword only needed on windows with MSVC installed
err = weave.inline(code,
['u', 'dx2', 'dy2', 'dnr_inv', 'nx', 'ny'],
type_converters=converters.blitz,
compiler = 'gcc')
return err

No comments:

Post a Comment

To add a link to text:
<a href="URL">Text</a>