Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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