File: class/Extras/Code/Misc/timerseqs.py

import time, sys
repouter = 1000        # build 1K result list 1K times
repinner = 1000        # 1K * 1K = 1M iterations per test

def runtest(func):
    start = time.clock()
    func()
    stop = time.clock()
    print func.__name__, '\t:', stop - start

def listcomp():
    for i in xrange(repouter):
        t = [x**2 for x in range(repinner)]

def mapfunc():
    for i in xrange(repouter):
        t = map((lambda x: x**2), range(repinner))

def forloop():
    for i in xrange(repouter):
        t = []
        for x in range(repinner):
            t.append(x**2)

def nestedcomp1():
    # but builds a longer list (1M)
    t = [x**2 for y in range(repouter) for x in range(repinner)]

def nestedcomp2():
    # but keeps many lists (1K * 1K)
    t = [[x**2 for x in range(repinner)] for y in range(repouter)]

def testcases():
    for i in range(2):
        runtest(listcomp)
        runtest(mapfunc)
        runtest(forloop)
        print '-'*20
    runtest(nestedcomp1)
    runtest(nestedcomp2)
    if sys.version_info[:2] >= (2, 4):
        # 2.4 generator expression syntax
        exec """def gencomp():
            for i in xrange(repouter):
                e = (x**2 for x in range(repinner))
                t = list(e)"""
        runtest(gencomp)

testcases()
raw_input('Test finished.')



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