[SciPy-user] MATLAB faster than Python (more code included)

Bryan Cole bryan at cole.uklinux.net
Wed Jul 5 16:32:36 EDT 2006


On Wed, 2006-07-05 at 11:00 +0200, William Hunter wrote:
> Robert;
> 
> Thanks for your reply and advise, I found <dgesv> through Google - you
> should've given me a STFW here... Thank you anyway.
> 
> I've attached MIF.py (and MIF.m for comparison). 
> 
> The function is part of a topology optimization routine (top.py)
> originally written in MATLAB. The number of times MIF is called is a
> function of the convergence criteria. For a sloppy convergence criteria
> and a very rough domain of 20x20 (i.e.,(nelx)x(nely)) elements, MIF is
> called 37 times. The finer the domain (one would typically want 200x200
> for example), the more calls to MIF.
> 
> The main script (top.py) takes 34 sec to complete for 20x20 elements, of
> which MIF's share is 15 sec.
> 
> If you run MIF() on its own you'll see that it is slow compared to the
> MATLAB one.

Well, I get a factor >2 speedup in the MIF.py script by vectorising the
inner loops:

from numpy import mgrid, sum
def MIF2(nelx=60,nely=20,rmin=1.5,x=zeros((20,60),\
                              float)+0.5,dc=randn(20,60)):
    dcNew = zeros_like(dc)
    round_rmin = int(round(rmin))
    for i in xrange(nelx):
        k_min, k_max = maximum(i-round_rmin,0),\
                minimum(i+round_rmin,nelx)
        for j in xrange(nely):
            l_min, l_max = maximum(j-round_rmin,0),\
                    minimum(j+round_rmin,nely)
            k,l = mgrid[k_min:k_max,l_min:l_max]
            fac = rmin-sqrt((i-k)**2+(j-l)**2)
            result = maximum(0,fac)*x[l,k]*dc[l,k]
            Sum = sum(maximum(0,fac).flat)
            dcNew[j,i] = sum(result.flat)/(Sum*x[j,i])
    return dcNew     

However, I would have thought this equally possible in the matlab
version. N.B. I've changed the local variable 'sum' to 'Sum', as I use
the numpy.sum function.

BC





More information about the SciPy-User mailing list