free-threading: Poor scaling with module level objects that are not tracked by the GC · Issue #163216 · python/cpython
Repository navigation
free-threading: Poor scaling with module level objects that are not tracked by the GC #163216
New issue
New issue
Backlog
Backlog
free-threading: Poor scaling with module level objects that are not tracked by the GC #163216 Labels
interpreter-core
performance
topic-free-threading
type-bug
Description
@johng's profile johng opened on Dec 5, 2026import gc
import sys
import threading
import time
ALLOWED_METHODS = frozenset({"GET", "HEAD", "POST", "PUT", "DELETE"})
LOOKUPS = 2_000_000
def lookup(n):
for _ in range(n):
"POST" in ALLOWED_METHODS
def throughput(nthreads):
"""Total lookups per second over nthreads worker threads."""
threads = [threading.Thread(target=lookup, args=(LOOKUPS,))
for _ in range(nthreads)]
start = time.perf_counter()
for t in threads:
t.start()
for t in threads:
t.join()
return nthreads * LOOKUPS / (time.perf_counter() - start)
def main():
nthreads = int(sys.argv[1]) if len(sys.argv) > 1 else 4
# Worker threads only, even for 1 thread: the main thread created the
# constant, and only other threads use the shared reference count.
one = throughput(1)
many = throughput(nthreads)
print(f"1 thread: {one / 1e6:6.1f}M lookups/s")
print(f"{nthreads} threads: {many / 1e6:6.1f}M lookups/s total"
f" = {many / one:.2f}x")
print()
print(f"Expected on a free-threaded build: close to {nthreads}x.")
if __name__ == "__main__":
main()
./python.exe frozenset_standalone_repro.py
1 thread: 64.6M lookups/s
4 threads: 7.4M lookups/s total = 0.11x
Expected on a free-threaded build: close to 4x.
This poor scaling is due to frozenset not being enabled for deferred reference counting. Interestingly it was enabled as part of #142843 and with that PR we get close to 4x scaling here. However two related changes broke that scaling. #140234 ("Do not track frozenset objects with immutables") and #144081 ("No deferred reference counting for untracked")
Those two changes combined re-introduced the overhead of accessing a module level variable for frozensets.
A proposed fix is to enable deferral and tracking module level fields via the the original module level specialisation path. Believe this would retain the origonal intention of the above two fixes whilst maintaining the scaling of module level objects in FT.
Metadata
Metadata
Assignees
No one assignedLabels
interpreter-core
performance
topic-free-threading
type-bug