Code speedup tips
Sean Richards
someone at invalid.com
Sun Mar 2 00:36:44 CET 2003
Hi,
Just started looking at Python as a tool for investigating 2d Cellular
Automata. I am a complete novice in both disciplines so be gentle (I
don't pretend to be a skilled programmer either) ;) Found some code for
a 1d CA which I have crudely modified to work with 2d CA. I would
appreciate some advice on how to make this code more efficient, as it
already takes about 1 minute with a 200X200 array on a 1.2ghz processor.
I can see that the nested loops are the bottleneck but what better
alternatives does Python have for iterating over a 2d array. I have
only being playing with Python for a very short time and there is so
much out there that I am getting myself a bit lost in all the
information. Anyway here is the code with a *very* simple rule as an
example - read it and weep :)
----8<-----------------------------------------------------------------
# Simple cellular automata - code 1022
# Rule specifies that a cell should become black if any
# of its neighbours were black on previous step
# Original code by Frank Buss - http://www.frank-buss.de/automaton/rule30.html
# import the Numeric module - used for the arrays
from Numeric import *
# import the Tk module - used to display the CA
from Tkinter import *
def CA_Function(Length):
# Create the two lattices
current = zeros((Length,Length),Int)
next = zeros((Length,Length),Int)
# Set the start cell to black
current[len(current)/2,len(current)/2] = 1
next[len(current)/2,len(current)/2] = 1
# Apply the rule
for step in xrange(1,(Length/2)-1):
for i in xrange(1,len(current)-1):
for j in xrange(1,len(current)-1):
if current[i-1,j]== 1 or current[i,j-1]== 1 or \
current[i,j+1]== 1 or current[i+1,j]== 1:
next[i,j] = 1
# Swap the lattices at each step
(current,next) = (next,current)
# Draw the lattice
CA_Draw(current)
def CA_Draw(Lattice):
for x in range(1,len(Lattice)-1):
for y in range(1,len(Lattice)-1):
if Lattice[x,y]:
img.put("black",(x,y))
else:
img.put("white",(x,y))
# Initialise the Tk interface
root = Tk()
root.title('2d CA')
# Create the empty image
Length = 200
img=PhotoImage(width=Length,height=Length)
# Apply the function
CA_Function(Length)
# Display image
lbl=Label(root,image=img)
lbl.pack()
root.mainloop()
----8<-----------------------------------------------------------------
On the 200x200 array that gives me 40,000 elements, I go over the entire
array 100 times -> 4,000,000 iterations
Then to fill the image is another 200x200 operations -> 40,000
Any tips on how to make this more efficient would be greatly appreciated.
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