Created
November 13, 2018 12:47
-
-
Save neoshrew/fee4aca6c36ef7c0083596def7b0f000 to your computer and use it in GitHub Desktop.
Perf examples for ymanb
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
$echo; for test in defaultdict setdefault check_in; do echo -n "${test} "; python3 -m timeit -s "from test import test_${test} as test_func" "test_func()"; done | |
defaultdict 1000 loops, best of 3: 999 usec per loop | |
setdefault 1000 loops, best of 3: 1.89 msec per loop | |
check_in 1000 loops, best of 3: 1.27 msec per loop |
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
from collections import defaultdict | |
from hashlib import md5 | |
n_classes = 10 | |
n_people = 10000 | |
# use md5 to get some pseudorandomly ordered "names", | |
# for the sorting to be a factor | |
data = [(i%n_classes, md5(bytes(i)).hexdigest()) | |
for i in range(n_people)] | |
def test_defaultdict(): | |
roster = defaultdict(list) | |
for class_, person in data: | |
roster[class_].append(person) | |
def test_defaultdict_sorted(): | |
roster = defaultdict(list) | |
for class_, person in data: | |
roster[class_].append(person) | |
roster[class_].sort() | |
def test_setdefault(): | |
roster = {} | |
for class_, person in data: | |
roster.setdefault(class_, []).append(person) | |
def test_setdefault_sorted(): | |
roster = {} | |
for class_, person in data: | |
this_class = roster.setdefault(class_, []) | |
this_class.append(person) | |
this_class.sort() | |
def test_check_in(): | |
roster = {} | |
for class_, person in data: | |
if class_ in roster: | |
roster[class_].append(person) | |
else: | |
roster[class_] = [person] | |
def test_check_in_sorted(): | |
roster = {} | |
for class_, person in data: | |
if class_ in roster: | |
roster[class_].append(person) | |
roster[class_].sort() | |
else: | |
roster[class_] = [person] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment