Skip to content

Instantly share code, notes, and snippets.

@kykyev
Last active December 16, 2015 22:09
Show Gist options
  • Select an option

  • Save kykyev/5504888 to your computer and use it in GitHub Desktop.

Select an option

Save kykyev/5504888 to your computer and use it in GitHub Desktop.
Python's containers look-up speed estimation
import contextlib
import time
import sys
@contextlib.contextmanager
def timer():
stat = lambda: None
start = time.time()
yield stat
end = time.time()
stat.msecs = (end - start) * 1000
KEYS = ['a', 'b', 'c', 'd', 'e']
CONTAINERS = {
'list': list(KEYS),
'tuple': tuple(KEYS),
'set': set(KEYS),
'frozenset': frozenset(KEYS),
'dict': dict(zip(KEYS, [1]*len(KEYS))),
}
def do_test(container_type):
try:
container = CONTAINERS[container_type]
except KeyError:
raise RuntimeError("Unknown container type")
else:
print
print type(container), container
print 'size in memory ->', sys.getsizeof(container)
with timer() as t:
for x in xrange(10000000):
'a' in container
print container_type, ':a:', t.msecs
with timer() as t:
for x in xrange(10000000):
'c' in container
print container_type, ':c:', t.msecs
with timer() as t:
for x in xrange(10000000):
'e' in container
print container_type, ':e:', t.msecs
print
do_test('list')
do_test('tuple')
do_test('set')
do_test('frozenset')
do_test('dict')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment