Improving scaling of creating lambda functions and other short lived functions · Issue #163240 · python/cpython
Repository navigation
Improving scaling of creating lambda functions and other short lived functions #163240
New issue
New issue
Backlog
Backlog
Improving scaling of creating lambda functions and other short lived functions #163240 Labels
interpreter-core
performance
topic-free-threading
type-feature
Description
@johng's profile johng opened on Dec 6, 2026When creating a function a global reference is created to it's module, incrementing it's shared reference count.
create function object
module = globals['__name__'] # the string "shop.orders"
Py_INCREF(module) # counter: 10 -> 11
func.__module__ = module
...lambda is used, then nothing points at it any more...
free function object
Py_DECREF(func.__module__) # counter: 11 -> 10
This can create scaling bottle necks for hot code paths which might be creating short lived functions such as for lambdas, generator expressions and closures.
If the module name __name__ was interned it would reduce the cost of the above because the shared reference count is not updated. If we do this explicitly in a micro benchmark we can see a clear scaling advantage.
import sys
import threading
import time
import types
CODE = """
def make_lambda():
return lambda: None
"""
def load_module(intern):
name = "".join(["shop.", "orders"]) # built at run time, like a submodule's
if intern:
name = sys.intern(name) # what the fix does in importlib
module = types.ModuleType(name)
exec(CODE, module.__dict__)
return module
def calls_per_second(make, nthreads, calls=300_000):
def worker():
for _ in range(calls):
make()
threads = [threading.Thread(target=worker) for _ in range(nthreads)]
start = time.perf_counter()
for t in threads:
t.start()
for t in threads:
t.join()
return nthreads * calls / (time.perf_counter() - start)
for intern in (False, True):
module = load_module(intern)
name = module.__name__
lambdas = [module.make_lambda() for _ in range(1000)]
print(f"interned={intern}: immortal={sys._is_immortal(name)}, "
f"lambda.__module__ is __name__: {lambdas[0].__module__ is name}, "
f"refcount with 1000 lambdas alive: {sys.getrefcount(name)}")
del lambdas
one = calls_per_second(module.make_lambda, 1)
eight = calls_per_second(module.make_lambda, 8)
print(f" 1 thread {one / 1e6:.1f}M lambdas/s, "
f"8 threads {eight / 1e6:.1f}M/s ({eight / one:.1f}x)")
python3.15t Tools/ftscalingbench/module_name_demo.py
interned=False: immortal=False, lambda. module is name : True, refcount with 1000 lambdas alive: 1005
1 thread 23.2M lambdas/s, 8 threads 7.2M/s (0.3x)
interned=True: immortal=True, lambda. module is name : True, refcount with 1000 lambdas alive: 3221225472
1 thread 28.5M lambdas/s, 8 threads 162.4M/s (5.7x)
With a full set of examples we have the following, and running with optimisations we have
x86 (Intel Xeon Platinum 8280, 16 vCPUs, Linux, PGO+LTO, GCC 14.2)
| Pattern | Code (in a package submodule) | T=4 | T=8 | T=12 | T=16 | Fixed ÷ stock throughput, T=16 |
|---|---|---|---|---|---|---|
| nqueens | len(set(vec[i] + i for i in cols)) |
3.0x → 3.7x | 4.6x → 6.3x | 5.2x → 6.9x | 5.5x → 7.1x | 1.30x |
| Closure creation (microbenchmark) | nested def f(): return i returned by _mk(i) |
1.1x → 3.9x | 1.2x → 6.5x | 1.4x → 7.5x | 1.6x → 7.2x | 4.6x |
| Closure callback per message | nested def reply(result): return (msg['id'], result) inside handle_message(msg) |
2.0x → 3.9x | 2.3x → 6.3x | 2.7x → 7.4x | 2.9x → 7.4x | 2.51x |
| Validator (shared inputs) | any(c.isdigit() for c in order['customer']) and sum(i['qty'] * i['price'] for i in order['items']) |
3.0x → 4.0x | 4.2x → 6.7x | 4.5x → 7.3x | 4.7x → 7.2x | 1.52x |
| Lambda sort key (shared inputs) | sorted(scores, key=lambda s: s[1], reverse=True)[:2] |
2.75x → 3.9x | 3.6x → 6.0x | 3.9x → 7.5x | 4.1x → 7.65x | 1.87x |
join() with a generator expression (shared inputs) |
','.join(str(v) for v in row) |
3.0x → 3.9x | 4.3x → 6.2x | 4.8x → 6.5x | 5.0x → 7.5x | 1.49x |
| Ceiling (CPU-only control) | ~3.9x | 5.5-6.6x | 6.3-7.5x | 7.0-7.5x |
There are a few options on when we can intern, such as at module creation or when loading the import. At import via importlib seemed most viable and removes any risk of short lived dynamic modules increasing memory usage.
Metadata
Metadata
Assignees
No one assignedLabels
interpreter-core
performance
topic-free-threading
type-feature