From d28571e2a399b07bdc9e9ae66719479d673e5b5e Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Wed, 23 Jul 2025 23:04:01 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Speed=20up=20method=20`Cod?= =?UTF-8?q?eFlashBenchmarkPlugin.pytest=5Fcollection=5Fmodifyitems`=20by?= =?UTF-8?q?=20670%=20in=20PR=20#574=20(`easier-benchmark`)=20Here=E2=80=99?= =?UTF-8?q?s=20how=20you=20can=20optimize=20your=20code=20for=20**speed**?= =?UTF-8?q?=20and=20**memory**=20while=20maintaining=20return=20values,=20?= =?UTF-8?q?behavior,=20and=20comments.=20I=20focused=20on=20making=20`pyte?= =?UTF-8?q?st=5Fcollection=5Fmodifyitems`=20faster=20by.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - **Avoiding function calls/attribute checks inside tight loops:** Since ideally `get_closest_marker` existence is consistent across items, fetch it once per item and cache the lookup. - **Reducing repeated work:** Move more work (e.g. creation of the skip marker) outside the inner loop. ### Changes and Optimizations. - **Cache Attribute**: `getattr(item, "get_closest_marker", None)` is used to avoid repeated `hasattr` checks or repeated attribute lookups. - **Reuse Marker Instance**: `skip_marker` is created once, not in every loop iteration. - **Skip on missing attribute** instead of raising. **This will speed up the loop by:** - Reducing per-item attribute lookup - Reducing decorator construction - Reducing function calls on items which don’t have `get_closest_marker` (if any) --- Let me know if you want further or different optimizations! --- codeflash/benchmarking/plugin/plugin.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/codeflash/benchmarking/plugin/plugin.py b/codeflash/benchmarking/plugin/plugin.py index a120a9496..a45974209 100644 --- a/codeflash/benchmarking/plugin/plugin.py +++ b/codeflash/benchmarking/plugin/plugin.py @@ -233,12 +233,16 @@ def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item if not config.getoption("--codeflash-trace"): return + skip_marker = pytest.mark.skip(reason="Test requires benchmark marker") for item in items: # Check for @pytest.mark.benchmark marker - if hasattr(item, "get_closest_marker"): - marker = item.get_closest_marker("benchmark") - if marker is None: - item.add_marker(pytest.mark.skip(reason="Test requires benchmark marker")) + get_marker = getattr(item, "get_closest_marker", None) + if get_marker is not None: + if get_marker("benchmark") is None: + item.add_marker(skip_marker) + else: + # If item does not have get_closest_marker (rare), skip it for correctness + continue # Benchmark fixture class Benchmark: # noqa: D106