Iteration style

Michael Hoffman m.h.3.9.1.without.dots.at.cam.ac.uk at example.com
Thu Sep 23 07:18:35 EDT 2004


Abdullah Khaidar wrote:

> Is there any iteration style we must use to get faster processing
> time?

Yes, definitely this one:

>>>>def useJoin():
> 
> 	list = [str(element) for element in range(5)]
> 	return "".join(list)

You aren't going to get the right results from your getTimer() function 
because you are just timing putting the function object on the stack, 
rather than actually calling it.

>>>>def getTimer():
> 
> 	from timeit import Timer
> 	t1 = Timer("useListIteration", "from __main__ import
> useListIteration")

should be t1 = Timer("useListIteration()", "from __main__ import 
useListIteration")

> 	print "Using list iteration: ", min(t1.repeat())

Of course now that you are actually calling a function, it should take a 
lot longer, so repeating it 3 * 1,000,000 times is way too many. I would 
change the number of integers you are concatenating from 5 to 1000 and 
run Timer.timeit(number=100) (repeats 3 * 100 times) instead.

 >>> getTimer()
Using list iteration:  0.751999855042
Using normal iteration:  0.766999959946
Using join:  0.446000099182

HTH,
--
Michael Hoffman



More information about the Python-list mailing list