import time
rpes = 10000
repsList = range(rpes)
def timer(func, *args, **kargs):
start = time.clock()
for i in repsList:
ret = func(*args, **kargs)
elapsed = time.clock() - start
return elapsed, ret
def forLoop():
res = []
for x in repsList:
res.append(abs(x))
return res
def listComp():
return [abs(x) for x in repsList]
def mapCall():
return list(map(abs, repsList))
def genExpr():
return list(abs(x) for x in repsList)
def genFunc():
def gen():
for x in repsList:
yield abs(x)
return list(gen())
print(sys.version)
for test in (forLoop, listComp, mapCall, genExpr, genFunc):
elapsed, result = timer(test)
print('-' * 33)
print('{0} : {1:.4f} => [{2}....{3}]'.format(test.__name__, elapsed, result[0], result[-1]))