From 84cc814eaf91609210fa263d72a525caf7e0788e Mon Sep 17 00:00:00 2001 From: Arthur Pastel Date: Wed, 7 Jun 2023 15:36:15 +0200 Subject: [PATCH] feat: add introspection benchmarks --- .github/workflows/ci.yml | 16 +++++++++ pyproject.toml | 3 ++ tests/benchmarks/test_bench_fibo.py | 53 +++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 tests/benchmarks/test_bench_fibo.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e4ba8e8..6c551ce 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,3 +54,19 @@ jobs: run: pip install pytest-benchmark~=4.0.0 py - name: Run tests run: pytest -vs + + benchmarks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up Python 3.12 + uses: actions/setup-python@v2 + with: + python-version: "3.11" + - name: Install local version of pytest-codspeed + run: pip install . + + - name: Run benchmarks + uses: CodSpeedHQ/action@main + with: + run: pytest tests/benchmarks/ --codspeed diff --git a/pyproject.toml b/pyproject.toml index 5b729dd..acb9553 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,6 +68,9 @@ use_parentheses = true force_grid_wrap = 0 float_to_top = true +[tool.pytest.ini_options] +addopts = "--ignore=tests/benchmarks" + [tool.coverage.run] branch = true [tool.coverage.report] diff --git a/tests/benchmarks/test_bench_fibo.py b/tests/benchmarks/test_bench_fibo.py new file mode 100644 index 0000000..eb2dc00 --- /dev/null +++ b/tests/benchmarks/test_bench_fibo.py @@ -0,0 +1,53 @@ +def recursive_fibonacci(n: int) -> int: + if n in [0, 1]: + return n + return recursive_fibonacci(n - 1) + recursive_fibonacci(n - 2) + + +def recursive_cached_fibonacci(n: int) -> int: + cache = {0: 0, 1: 1} + + def fibo(n) -> int: + if n in cache: + return cache[n] + cache[n] = fibo(n - 1) + fibo(n - 2) + return cache[n] + + return fibo(n) + + +def iterative_fibonacci(n: int) -> int: + a, b = 0, 1 + for _ in range(n): + a, b = b, a + b + return a + + +def test_iterative_fibo_10(benchmark): + @benchmark + def _(): + iterative_fibonacci(10) + + +def test_recursive_fibo_10(benchmark): + @benchmark + def _(): + recursive_fibonacci(10) + + +def test_recursive_fibo_20(benchmark): + @benchmark + def _(): + recursive_fibonacci(20) + + +def test_recursive_cached_fibo_10(benchmark): + @benchmark + def _(): + recursive_cached_fibonacci(10) + + +def test_recursive_cached_fibo_100(benchmark): + @benchmark + def _(): + recursive_cached_fibonacci(100)