code optimization (calc PI)

Matimus mccredie at gmail.com
Wed Jan 3 12:14:26 EST 2007


Using the '+' operator for string concatonation can be slow, especially
when done many times in a loop.

>    pi = pi + str("%04d" % int(e + d/a))  ## this should be fast?! I dont

The accepted solution would be to make pi an array and append to the
end...

pi = [] #create the array (empty)
...
...
pi.append(str("%04d"%int(e+d/a))) # append to it

And when it is time to print the results do the following:

print "".join(pi)

It may look strange, but it is a common Python idiom. You might also
look into an optimizer such as psycho: http://psyco.sourceforge.net/.




More information about the Python-list mailing list