# modified by cpbotha@ieee.org from this posting: # http://mail.python.org/pipermail/python-list/2000-December/022606.html import time import operator def withMapSQR(inList): return map(lambda x: x**2.0, inList) def withMapDBL(inList): return map(operator.mul, inList, inList) def withLCSQR(inList): return [x**2.0 for x in inList] def withLCDBL(inList): return [x*x for x in inList] def withLoopSQR(inList): l = len(inList) result = [None]*l for i in range(l): result[i] = inList[i]**2 return result def withLoopDBL(inList): l = len(inList) result = [None]*l for i in range(l): result[i] = inList[i]*inList[i] return result def stopWatch(function, N=100*1000): start = time.clock() nlist = map(lambda x: 1.0 * x, range(N)) function(nlist) stend = time.clock() return stend-start print "Using map and lambda (**2): %f" % stopWatch(withMapSQR) print "Using map without lambda (list doubling): %f" % stopWatch(withMapDBL) print "Using list-comprehension (**2): %f" % stopWatch(withLCSQR) print "Using list-comprehension (elem doubling): %f" % stopWatch(withLCDBL) print "Using a simple loop (**2): %f" % stopWatch(withLoopSQR) print "Using a simple loop (elem doubling): %f" % stopWatch(withLoopDBL)