Skip to content

free-threading: Poor scaling with module level objects that are not tracked by the GC #163216

Backlog

Description

@johng
import 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.

Activity

  1. added
    interpreter-core
    performance
    type-bug
    on Dec 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coreperformancetopic-free-threadingtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions