Last active
December 16, 2015 22:09
-
-
Save kykyev/5504888 to your computer and use it in GitHub Desktop.
Python's containers look-up speed estimation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 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 | |
| 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