Skip to content

Instantly share code, notes, and snippets.

@zahradil
Created August 16, 2012 07:49
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 zahradil/3368186 to your computer and use it in GitHub Desktop.
Save zahradil/3368186 to your computer and use it in GitHub Desktop.
setdault too slow problem
import timeit
def debug(func, var):
print "Timing", func,
stmt = lambda: func(var)
tm = timeit.Timer(stmt=stmt)
res = tm.timeit(10000)
lst = stmt()
print "%1.10f" % (res*1000)
for key,val in sorted(lst.iteritems(), key=lambda x: x[1]):
print "%4dx %s" % (len(val),key)
print ""
def test1(iterable):
values = {}
for element in iterable:
values.setdefault(element.name, []).append(element)
return values
def test2(iterable):
values = {}
for element in iterable:
if element.name not in values:
values[element.name]=[element]
else:
values[element.name].append(element)
return values
def test3(iterable):
values = {}
cur_name = None
cur_list = None
for element in iterable:
if element.name != cur_name:
values[cur_name] = cur_list
cur_name = element.name
cur_list = []
cur_list.append(element)
if cur_list:
values[cur_name] = cur_list
del values[None]
return values
class obj(object):
def __init__(self, name, val):
self.name = name
self.val = val
xx = [[obj("name%d" % (i), i*j) for i in range(10)] for j in range(5)]
x = sorted(sum(xx, []), key=lambda x: x.name)
debug(test1,x)
debug(test2,x)
debug(test3,x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment