Skip to content

Instantly share code, notes, and snippets.

@davidwtbuxton
Created March 15, 2012 11:57
Show Gist options
  • Save davidwtbuxton/2043869 to your computer and use it in GitHub Desktop.
Save davidwtbuxton/2043869 to your computer and use it in GitHub Desktop.
Comparison of dictionary types
# Comparison of dictionary types
# http://www.reddit.com/r/Python/comments/qxjho/sdict_sorted_dictionary_for_python_sdict_is_a/
from sdict import Dict
from collections import OrderedDict
import itertools
import timeit
def keygen():
"""A generator that produces all possible combinations of letters."""
from string import ascii_lowercase
for n in itertools.count(1):
if n >= len(ascii_lowercase):
break
for combo in itertools.product(ascii_lowercase, repeat=n):
yield ''.join(combo)
def new_keys(n):
"""Returns a new list of the first n combinations of letters."""
return list(itertools.islice(keygen(), 0, n))
def test1(cls, keys):
"""Create a new dictionary and insert keys."""
d = cls()
for k in keys:
d[k] = k
if __name__ == "__main__":
nkeys = 1000 # Size of test dictionary
runs = 1000 # Number of runs for each test
setup = 'from __main__ import new_keys, Dict, OrderedDict, test1; keys = new_keys(%d)' % nkeys
tests = (
'test1(dict, keys)',
'test1(OrderedDict, keys)',
'test1(Dict, keys)',
)
print 'Time to insert %d keys in a dictionary, %d runs' % (nkeys, runs)
for test in tests:
print test
print timeit.timeit(test, setup, number=runs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment