Repository navigation
Description
Bug report
Remaining scaling bugs
- dataclass
- namedtuple
- enum
Bug description:
When constructing dataclass or NamedTuple instances on multiple threads (on a free threading build), or accessing enum class attributes, performance doesn't scale when using multiple threads.
Regular class example (scales well):
# b_regular_class.py
from threading import Thread
from time import time
import sys
class Foo:
def __init__(self, x):
self.x = x
niter = 5 * 1000 * 1000
def benchmark(n):
for i in range(n):
Foo(x=1)
for nth in (1, 4):
t0 = time()
threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"{nth=} {(time() - t0) / nth}")Dataclass example (doesn't scale well):
# b_dataclass.py
from threading import Thread
from dataclasses import dataclass
from time import time
import sys
@dataclass
class Foo:
x: int
niter = 5 * 1000 * 1000
def benchmark(n):
for i in range(n):
Foo(x=1)
for nth in (1, 4):
t0 = time()
threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"{nth=} {(time() - t0) / nth}")Named tuple example (doesn't scale well):
# b_namedtuple.py
from threading import Thread
from typing import NamedTuple
from time import time
import sys
class Foo(NamedTuple):
x: int
niter = 5 * 1000 * 1000
def benchmark(n):
for i in range(n):
Foo(x=1)
for nth in (1, 4):
t0 = time()
threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"{nth=} {(time() - t0) / nth}")Enum example (doesn't scale well):
# b_enum.py
from threading import Thread
from time import time
from enum import Enum
import sys
class Foo(Enum):
X = 1
Y = 2
niter = 5 * 1000 * 1000
def benchmark(n):
for i in range(n):
Foo.X
Foo.Y.value
for nth in (1, 4):
t0 = time()
threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"{nth=} {(time() - t0) / nth}")Results on recent main branch (running on an EC2 instance):
(cpython-dev) jukka@jukka-coder-dbx free-threading-benchmarks $ py b_regular_class.py
nth=1 1.1085155010223389
nth=4 0.2796591520309448
(cpython-dev) jukka@jukka-coder-dbx free-threading-benchmarks $ py b_dataclass.py
nth=1 1.1910037994384766
nth=4 1.0931583642959595
(cpython-dev) jukka@jukka-coder-dbx free-threading-benchmarks $ py b_namedtuple.py
nth=1 1.5688557624816895
nth=4 2.0257126092910767
(cpython-dev) jukka@jukka-coder-dbx free-threading-benchmarks $ py b_enum.py
nth=1 0.9439797401428223
nth=4 2.272495985031128
The expected behavior is that when using 4 threads (nth=4), the elapsed time per benchmark iteration (the second printed value) goes down significantly compared to when using a single thread (nth=1), which happens with the first benchmark (b_regular_class.py) but not the others.
cc @colesbury (we discussed this at CPython Core Dev Sprint in person)
CPython versions tested on:
CPython main branch
Operating systems tested on:
Linux
Linked PRs
- gh-139103: fix free-threading
dataclass.__init__perf issue #141596 - Draft: gh-139103: Use _PyObject_GetMethodStackRef for slot_tp_new #141603
- [3.14] gh-139103: fix free-threading
dataclass.__init__perf issue (gh-141596) #141750 - gh-139103: Improve namedtuple scaling in free-threaded build #144332
- gh-139103: Use METH_FASTCALL for tp_new_wrapper #144406
- gh-139103: Use borrowed references for positional args in _PyStack_UnpackDict #144407
- gh-139103: Improve enum free-threaded scaling #144977
- gh-139103: Defer reference count mutable class attributes #155876
Activity
LindaSummer commentedon Nov 21, 2025
Hi @colesbury ,
Wish you a good day! 😊
I have some findings about the
Enumperf issue, and please correct me if I make a mistake in my analysis. 😊My guessing about the problem
It should not be an issue directly related to
Enum. It should be the descriptor's performance issue.My analysis steps
Here is my configure for building cpython.
./configure --disable-gil \ --prefix=$PWD/build-non-gil-release-perf-enabled \ LDFLAGS="-Wl,-rpath=$PWD/build-non-gil-release-perf-enabled/lib" \ CFLAGS="-g -fno-omit-frame-pointer"Construct two cases with only the descriptors' read/write
The descriptor read
The test case is below.
I ran perf with below command. My filename is
./edward-test-descr-read.py.Here is the flamegraph.
The descriptor write
The test case is below. My test filename is
./edward-test-descr-write.py.I ran perf command below.
Here is the flamegraph file.
My analysis conjecture
It seems that the
_PyType_LookupStackRefAndVersionis the bottleneck.I check its implementation and find it seems waiting for all threads in non-gil mode
cpython/Objects/typeobject.c
Lines 6120 to 6214 in 49ff8b6
My guessing of the performance issue
I plan to research the
_PyType_LookupStackRefAndVersionfunction and try to find a solution.But I'm not sure whether my analysis and solution direction are correct.
Please help correct me on my report if there is any mistake. 😊
Thanks very much!
Best Regards,
Edward
colesbury commentedon Nov 21, 2025
The setter for a descriptor is
__set__, not__setattr__. I think you are setting the instance attribute in your benchmark, not invoking the descriptor.LindaSummer commentedon Nov 22, 2025
Hi @colesbury ,
Thanks very much for your correction! ❤
I will try to continue investigating this problem.
Best Regards,
Edward
LindaSummer commentedon Nov 30, 2025
Hi @colesbury ,
Sorry to bother you again.
I have some new findings that the
__set__performance is improved to a good result, but the descriptor__get__issue still exists and is mitigated by the case that confused me.I want to get some suggestions from you.
Here is my testing patch LindaSummer@4737a45 .
I added code below in both
_PyObject_GenericGetAttrWithDictand_PyObject_GenericSetAttrWithDict.Below are test cases and test results in main and my test branch.
I have used a new computer with better performance, so the baseline result improved compared to my previous testing in the above conversation.
__set__testTest case:
Result without my patch.
Result with my patch.
The performance has improved significantly.
__get__testTest case:
Result without my patch.
Result in my test branch.
But when I uncommented the two-line warm-up codes, the performance improved.
It seems the performance improvement is 1x.
I'm not sure the root cause of the
__get__and whether my patch for__set__is good.Hope to get a suggestion from you!
Wish you a good day!
Best Regards,
Edward
pythongh-139103: fix free-threading `dataclass.__init__` perf issue (p…
LindaSummer commentedon Dec 6, 2025
Hi @colesbury ,
I have some findings on this problem and want to get some guidance of the solution.
Please correct me if I made any mistake. 😊
My temporay patch to prove my guessing
After going through the code and debugging, I find that the difference between a descriptor getter and a regular class is here.
cpython/Objects/typeobject.c
Lines 6381 to 6391 in 5be3405
So the performance downgrade should be caused be the
meta_get.It is the
slot_tp_descr_getwhen this callback invoked.cpython/Objects/typeobject.c
Lines 10837 to 10860 in 5be3405
But as we could see here at the end of the function, it invokes
Py_DECREF(get);.The type cache in
_PyType_LookupRefworks well.But in free threading senario, we probably don't in same thread with the creator of type.
So it goes into the loop heavily.
cpython/Objects/object.c
Lines 370 to 404 in 5be3405
I use below patch to disable the decref and the result imrpoved about 1.3x comapring to current performance.
Here is my test sample.
Before applied the temporary patch, below is the result.
After applied the patch, below is the result.
We could see it improved a little.
My investogation for the behavior.
Perf report
First I run with perf and got below flamegraph.
We cloud find below samples in
slot_tp_descr_get.We could find that it cost a lot of time in
slot_tp_descr_get->Py_DECREF->_Py_DecRefShared->_Py_DecRefSharedDebug->_Py_DecRefSharedIsDead->_Py_atomic_compare_exchange_ssize.This is the bottleneck in the decrement for non-local objects.
PyStats
I enabled statistics in build and get below diff for a
SimpleClassand aBarDescriptor.Here are my test code.
Below is the diff i found in the two cases.
We could find that the below unexpected behavior.
As we could see the cache works well.
My conculsion
I think that we should have a way to borrow a reference of
getrather than directly increment and decrement it.But I have no good idea for this.
Could you give me some suggestions and correct me if I made any mistakes? 😊
Wish you a good day!
Best Regards,
Edward
pythongh-139103: fix free-threading `dataclass.__init__` perf issue (p…
pythongh-139103: Improve namedtuple scaling in free-threaded build
pythongh-139103: Use METH_FASTCALL for tp_new_wrapper
pythongh-139103: Use borrowed references for positional args in _PySt…
gh-139103: use `METH_FASTCALL` for tp_new_wrapper (#144406)
pythongh-139103: use `METH_FASTCALL` for tp_new_wrapper (python#144406)
gh-139103: Use borrowed references for positional args in _PyStack_Un…
Merge branch 'main' into pythongh-139103-named-tuple
Merge branch 'main' into pythongh-139103-named-tuple
gh-139103: Improve namedtuple scaling in free-threaded build (gh-144332)
pythongh-139103: use `METH_FASTCALL` for tp_new_wrapper (python#144406)
pythongh-139103: Use borrowed references for positional args in _PySt…
pythongh-139103: Improve namedtuple scaling in free-threaded build (p…
pythongh-139103: Improve enum free-threaded scaling
pythongh-139103: Improve namedtuple scaling in free-threaded build (p…
johng commentedon Aug 16, 2026
Also see this on various class/instance attributes in addition to the above PR, shall I be putting these in a new issue?
./python_main.exe Tools/ftscalingbench/ftscalingbench.py shared_instance_attribute
Running benchmarks with 18 threads
shared_instance_attribute 25.0x slower
pythongh-139103: Test deferred refcount of mutable class attributes
johng commentedon Nov 20, 2026
@eendebakpt would you mind mind taking a look at the above, thanks!
pythongh-139103: Address review comments