Last active
March 29, 2022 13:35
-
-
Save Bobsans/e501e1bec057767bb5065daddef132a6 to your computer and use it in GitHub Desktop.
Testing different python code performance
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
| # Windows 10, x64 | |
| # Python 3.8.5 | |
| def sep(a=None, b=None): | |
| return {**({'a': a} if a else {}), **({'b': b} if b else {})} | |
| def comp(a=None, b=None): | |
| return {k: v for k, v in {'a': a, 'b': b}.items() if v} | |
| def simp(a=None, b=None): | |
| res = {} | |
| if a: | |
| res['a'] = a | |
| if b: | |
| res['b'] = b | |
| return res | |
| def test(iters=1000): | |
| import time | |
| for f in [sep, comp, simp]: | |
| total = 0 | |
| for y in reversed(range(iters)): | |
| start = time.time() | |
| for x in range(iters): | |
| f(x, y) | |
| total += (time.time() - start) | |
| print(f'{f.__name__}: {total / iters:.6f}') | |
| test(10000) | |
| # sep: 0.001905 | |
| # comp: 0.004173 | |
| # simp: 0.001467 | |
| # ------------------------------------------------------------------------------ | |
| # Array append | |
| # | |
| # Windows 11, x64 | |
| # Python 3.10.2 | |
| # ------------------------------------------------------------------------------ | |
| def append(a, v): | |
| a.append(v) | |
| return a | |
| def plus(a, v): | |
| a += [v] | |
| return a | |
| def extend(a, v): | |
| return [*a, v] | |
| def test(fns, els=1000, its=1000): | |
| for fn in fns: | |
| sum = 0 | |
| for _ in range(its): | |
| start = time.monotonic_ns() | |
| arr = [] | |
| for v in range(els): | |
| fn(arr, v) | |
| sum += time.monotonic_ns() - start | |
| print(f'{fn.__name__}: {sum / its}') | |
| test([append, plus, extend], 1000, 10000) | |
| # append: 86000.0 | |
| # plus: 118700.0 | |
| # extend: 101600.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment