[Numpy-discussion] How to speed up this function?
Nadav Horesh
nadavh at visionsense.com
Wed Dec 6 02:05:06 EST 2006
You can speed it up easily by avoiding the loop. The main idea is to
replace the indexing of the type [i+1,j], [i-1,j], [i,j+1], [i,j-1] by
the appropriate slicing.
For example
for i in xrange(1,n):
for j in xrange(1,m)
a[i,j] = b[i-1,j] + c[i,j+1]
can be replaced by
a[1:,:-1] = b[:-1] + c[:,1:]
Nadav.
-----Original Message-----
From: numpy-discussion-bounces at scipy.org
[mailto:numpy-discussion-bounces at scipy.org] On Behalf Of
fsenkel at verizon.net
Sent: Monday, December 04, 2006 05:28
To: numpy-discussion at scipy.org
Subject: [Numpy-discussion] How to speed up this function?
Hello,
I'm taking a CFD class, one of the codes I wrote runs very slow. When I
look at hotshot is says the function below is the problem. Since this is
an explicit step, the for loops are only traversed once, so I think it's
caused by memory usage, but I'm not sure if it's the local variables or
the loop? I can vectorize the inner loop, would declaring the data
structures in the calling routine and passing them in be a better idea
than using local storage?
I'm new at python and numpy, I need to look at how to get profiling
information for the lines within a function.
Thank you,
Frank
PS
I tried to post this via google groups, but it didn't seem to go
through, sorry if it ends up as multiple postings
def findw(wnext,wprior,phiprior,uprior,vprior):
#format here is x[i,j] where i's are rows, j's columns, use flipud()
to get the
#print out consistent with the spacial up-down directions
#assign local names that are more
#inline with the class notation
w = wprior
phi = phiprior
u = uprior
v = vprior
#three of the BC are known so just set them
#symetry plane
wnext[0,0:gcols] = 0.0
#upper wall
wnext[gN,0:gcols] = 2.0/gdy**2 * (phi[gN,0:gcols] -
phi[gN-1,0:gcols])
#inlet, off the walls
wnext[1:grows-1,0] = 0.0
upos = where(u>0)
vpos = where(v>0)
Sx = ones_like(u)
Sx[upos] = 0.0
Sy = ones_like(v)
Sy[vpos] = 0.0
uw = u*w
vw = v*w
#interior nodes
for j in range(1,gasizej-1):
for i in range(1,gasizei-1):
wnext[i,j] =( w[i,j] + gnu*gdt/gdx**2 * (w[i,j-1] -
2.0*w[i,j] + w[i,j+1]) +
gnu*gdt/gdy**2 * (w[i-1,j] - 2.0*w[i,j] +
w[i+1,j]) -
(1.0 - Sx[i,j]) * gdt/gdx * (uw[i,j] -
uw[i,j-1]) -
Sx[i,j] * gdt/gdx * (uw[i,j+1] - uw[i,j]) -
(1.0 - Sy[i,j]) * gdt/gdy * (vw[i,j] -
vw[i-1,j]) -
Sy[i,j] * gdt/gdy * (vw[i+1,j] - vw[i,j]) )
## print "***wnext****"
## print "i: ", i, "j: ", j, "wnext[i,j]: ", wnext[i,j]
#final BC at outlet, off walls
wnext[1:grows-1,gM] = wnext[1:grows-1,gM-1]
_______________________________________________
Numpy-discussion mailing list
Numpy-discussion at scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion
More information about the NumPy-Discussion
mailing list