Code speedup tips
Sean Richards
someone at invalid.com
Sun Mar 2 02:47:23 EST 2003
On Sun, 02 Mar 2003 02:02:23 GMT, Carl Banks wrote:
[Excellent description of array slicing snipped]
Thanks Carl that was just what I needed. I had to draw the array slices
on a piece of graph paper to get a complete idea of what was happening
but I have now got my head around it. That is such a simple concept
(once you understand it) and so powerful. Just by altering the
combination of array slices I can create any neighbourhood I want. That
has made my day - thankyou :)
> Here is how I rewrote CA_Function. There are some details in it I've
> left unexplained; feel free to ask for a clarification:
>
>
> def CA_Function(Length,Steps):
> # Create the two lattices
> current = zeros((Length,Length),Int)
> workspace = zeros((Length-2,Length-2),Int)
>
> # Create slices of the current lattice
> # We don't have to do this every step because slicing shares memory
> left = current[0:-2,1:-1]
> up = current[1:-1,0:-2]
> right = current[2:,1:-1]
> down = current[1:-1,2:]
>
> # Set the start cell to black
> current[Length/2,Length/2] = 1
>
> # Apply the rule
> for step in xrange(Steps):
> # In the workspace, add the shifted lattices
> # This uses a bunch of += because it's faster
> workspace[:] = left
> workspace[:] += up
> workspace[:] += right
> workspace[:] += down
> # Set the current lattice
> current[1:-1,1:-1] = where(workspace,1,0)
OK this was a big improvement. Using the original nested loop version it
took ~12min for a 500x500 array, using array slices dropped the time to
~1min. That is a pretty significant reduction. One small thing I needed
to do to get the rule to work correctly was add the line ..
'workspace[:] += current[1:-1,1:-1]'
when you calculate the workspace. If we don't do this then on step 2 the
centre pixel becomes white instead of staying black. This effect
propagates until the end result is a diamond of alternating black and
white pixels instead of a solid black diamond.
That was a great help Carl, my total Python 'uptime' is only a couple of
hours but it looks like it is going to be an excellent tool.
Thanks, Sean
--
+---------------------------------------------------------------+
| All spelling errors are intentional and are there to show new |
| and improved ways of spelling old words. |
+---------------------------------------------------------------+
More information about the Python-list
mailing list