Created
May 9, 2023 07:48
-
-
Save nyggus/cd41a181ad2e23425279db1961438ca4 to your computer and use it in GitHub Desktop.
This file contains 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 timeit | |
import pprint | |
import rounder # requires installation from PyPi | |
def compare( | |
__snippet1, | |
__snippet2, | |
*args, | |
number=10_000_000, | |
repeat=7, | |
setup="from collections import UserDict"): | |
snippets = [__snippet1, __snippet2, *args] | |
results = {} | |
for i, snippet in enumerate(snippets): | |
name = snippet if len(snippet) < 30 else f"snippet {i + 1}" | |
results[name] = min(timeit.repeat( | |
snippet, number=number, repeat=repeat, setup=setup | |
)) / number, | |
results = rounder.signif_object(results, digits=4) | |
pprint.pprint(results) | |
setup = """from collections import UserDict | |
from collections.abc import Sequence | |
from typing import Callable | |
def try_calculate(func: Callable, *args, **kwargs): | |
try: | |
return func(*args, **kwargs) | |
except TypeError: | |
return float("nan") | |
class RichDict(dict): | |
def summarize(self): | |
return summarize(self) | |
def summarize(d: dict): | |
measures_seq = { | |
"sum": sum, | |
"n": len, | |
"mean": lambda x: sum(x) / len(x), | |
} | |
measures_str = { | |
"n": len, | |
} | |
statistics = {} | |
for k, v in d.items(): | |
if isinstance(v, str): | |
measures = measures_str | |
elif isinstance(v, Sequence): | |
measures = measures_seq | |
else: | |
continue | |
statistics[k] = { | |
name: try_calculate(func, v) | |
for name, func | |
in measures.items() | |
} | |
return statistics | |
d = { | |
'x': [i**2 for i in range(1000)], | |
'y': "This is just a text, and nothing else matters.", | |
'z': [12, 33.33, "forget it", 354.444], | |
'q': {((i + 1) / i)**2 for i in range(1, 100_000)} | |
} | |
rd = RichDict(d) | |
""" | |
compare( | |
"summarize(d)", | |
"rd.summarize()", | |
setup=setup, | |
number=1_000_000 | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment