Skip to content

Optimize Network.run(): Make gc.collect() conditional (Step 1 for #1823) - #1843

Closed
AxelNoun wants to merge 1 commit into
brian-team:masterfrom
AxelNoun:optimise-gc-collect
Closed

AxelNoun wants to merge 1 commit into
brian-team:masterfrom
AxelNoun:optimise-gc-collect

Conversation

@AxelNoun

Copy link
Copy Markdown
Contributor

Context & Strategy

This PR is a first, iterative step towards addressing the broader test suite speed issue (#1823). Because a comprehensive solution to the test suite speed will take time, my strategy is to tackle the bottlenecks in measured, incremental stages. This allows us to validate early wins, raise awareness of specific performance traps, and ensure zero regressions before moving on to larger architectural discussions (like unit vs. integration tests).

What

Network.run() calls gc.collect() unconditionally at the start of every run (core/network.py:1110). Its only purpose is to force __del__ on unused Brian objects to fire immediately, so the "object was never run" warning can be emitted.

That warning is itself gated by prefs.logging.warn_for_unused_objects (checked first thing in __del__, see core/base.py) — so when that preference is False, gc.collect() does nothing observable. This PR simply makes the call conditional on the same preference.

-        # This will trigger warnings for objects that have not been included in a network
-        gc.collect()
+        # This will trigger warnings for objects that have not been included in a network.
+        # Only necessary if such warnings are enabled, since gc.collect() can be a
+        # significant fraction of run() overhead, especially for short or no-op runs.
+        if prefs.logging.warn_for_unused_objects:
+            gc.collect()

Why this is behavior-preserving

__del__ already checks prefs.logging.warn_for_unused_objects before doing anything. Skipping the gc.collect() call when that preference is False cannot change anything the user observes — it only changes when unreferenced objects get swept, not whether a warning fires (it never would have).

The test harness itself sets warn_for_unused_objects = False for the codegen_independent/numpy/cython test runs, so this provides a pure speedup there with zero behavior change. Furthermore, test_unused_object_warning and test_magic_unused_object both explicitly set the preference to True before testing, and continue to pass unmodified.

Measurements (and why they disagree across machines)

We measured this on two independent setups, using the official brian2.test() preference/device plumbing to match CI conditions.

Scenario Linux (1 vCPU, Python 3.12) Windows (Python 3.14)
gc.collect() share of codegen_independent suite ~45–50% (test_neurongroup.py) ~25% (test_synapses.py) → ~1–2% on a tight run
(0*ms) loop 500× run(0*ms), warn=False gc.collect(): 37.9s of ~40s total (>90%)

These numbers disagree, and we think we know why: gc.collect()'s cost here isn't proportional to anything the test does — it's the fixed cost of scanning everything already tracked by the GC once brian2 (and numpy/cython) is imported. On our Linux box:

>>> len(gc.get_objects())     # bare Python: 8,507
>>> import numpy              # → 19,497
>>> import brian2             # → 142,028
>>> # gc.collect() timing:  0.001s (bare) → 0.005s (numpy) → 0.08s (brian2)

That ~80ms baseline is paid on every gc.collect() call regardless of how many test-created objects exist. The relative impact of this fix will vary by machine/Python version, so please read "45-50%" as the multiplier we could verify, not a universal constant.

Next Steps & Out of Scope

The broader plan: I want to gather real numbers on cpp_standalone (which dominates total suite time by roughly an order of magnitude over numpy/cython in our measurements) before proposing the next steps for the larger #1823 conversation.

Unrelated failing tests: While testing this, we hit an apparently pre-existing issue. Running the full codegen_independent marker set for test_network.py in one session intermittently fails 4 tests (test_network_schedule_change, test_schedule_warning, test_scheduling_summary_magic, test_scheduling_summary) and can hang on test_magic_network. This is reproducible on master as well. Looks like leftover device/clock state leaking. I didn't want to scope-creep this PR with an unrelated fix.

@AxelNoun AxelNoun closed this Jun 25, 2026
@AxelNoun
AxelNoun deleted the optimise-gc-collect branch June 25, 2026 04:30
mstimberg pushed a commit that referenced this pull request Sep 21, 2026
…s are enabled

The explicit garbage collection at the start of Network.run() only exists to raise the warning from BrianObject.__del__ for objects that were never included in a network, and that warning is already gated by the logging.warn_for_unused_objects preference. Skip the collection when the preference is disabled, document the link in the preference description, and add a regression test. First step towards #1823, supersedes #1843.

Co-authored-by: Cursor <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant