Skip to content

Instantly share code, notes, and snippets.

@aaronasterling
Created November 28, 2010 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronasterling/718629 to your computer and use it in GitHub Desktop.
Save aaronasterling/718629 to your computer and use it in GitHub Desktop.
import itertools
def pyfunc_fastest(x):
t = []
lenList = len(x)
extend = t.extend
for l in xrange(0, lenList):
extend([x[l]] * (lenList - l))
def pyfunc_iadd(x):
t = []
lenList = len(x)
for l in range(0, lenList):
t += [x[l]] * (lenList - l)
def pyfunc_xrange(x):
t = []
lenList = len(x)
for l in xrange(0, lenList):
t.extend([x[l]] * (lenList - l))
def pyfunc_local_extend(x):
t = []
lenList = len(x)
extend = t.extend
for l in range(0, lenList):
extend([x[l]] * (lenList - l))
def Ishpeck(l):
nl = []
i = 0
while len(l[i:])>0:
nl.extend( [l[i]]*len(l[i:]) )
i+=1
def JohnKugleman(items):
[item for i, j in enumerate(items) for item in [j] * (len(items) - i)]
def Ignacio(l):
list(itertools.chain.from_iterable(itertools.repeat(e, len(l) - i)
for i, e in enumerate(l)))
def pyfunc(x):
t = []
lenList = len(x)
for l in range(0, lenList):
t.extend([x[l]] * (lenList - l))
def FabrizioM(alist):
[x for idx, value in enumerate(alist)
for x in itertools.repeat(value, len(alist) - idx)]
def gen_indices(list_length):
for index in range(list_length):
for _ in range(list_length - index):
yield index
def Bwmat(x):
[list_[i] for i in gen_indices(len(list_))]
list_ = range(100)
if __name__ == '__main__':
results = {}
import timeit
mod_name = 'fastlist'
functions = (pyfunc, Ignacio, JohnKugleman, JohnKugleman,
Ishpeck, FabrizioM, Bwmat, pyfunc_fastest,
pyfunc_xrange, pyfunc_iadd, pyfunc_local_extend,
pyfunc_enumerate)
setup = 'from {0} import '.format(mod_name)
setup += ', '.join(f.__name__ for f in functions)
setup += ', gen_indices, list_'
for func in functions:
func_name = func.__name__
command = "{0}(list_)".format(func_name)
t = timeit.Timer(command, setup)
results[func_name] = 1000000 * t.timeit(number=10000)/10000
for name, result in sorted(results.items(), key=lambda x: x[1]):
print "{0}: {1} usecs".format(name, result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment