File: timeSEQ.py

# time sequence operations performance

import time, sys
timeFunc = time.clock
repsList = list(range(1000))            # prebuild lists to remove cost from test
sizeList = list(range(-5000, 5000))     # force list for 3.0 too, else a generator

def tester(func, *args):
    startTime = timeFunc()
    for i in repsList:
        result = func(*args)
    elapsed = timeFunc() - startTime
    return elapsed, result


def process(I): return I * 2                     # or abs(x)

def forStatement():
    res = []
    for x in sizeList:
        res.append(process(x))                   # or inline: x * 2, abs(x)
    return res

def listComprehension():
    return [process(x) for x in sizeList]        # or inline: x * 2, abs(s)

def mapFunction():
    return list(map(process, sizeList))          # force list for 3.0 too, else a generator

def generatorExpression():
    return list(process(x) for x in sizeList)    # force list on both 2.6 and 3.0


print (sys.version)
tests = (forStatement, listComprehension, mapFunction, generatorExpression)
for testfunc in tests:
    elapsed, result = tester(testfunc)
    print ( '%-20s => %.3f, %s...%s' % (testfunc.__name__, elapsed, result[:2], result[-2:]))

   #same as:
   #print ( '{0:<20} => {1:.3f}, {2}...{3}'.format(testfunc.__name__, elapsed, result[:2], result[-2:]))



[Home page] Books Code Blog Python Author Train Find ©M.Lutz