Skip to content

Commit 0c01090

Browse files
authored
GH-139951: Fix major GC performance regression (GH-140262)
* Count number of actually tracked objects, instead of trackable objects. This ensures that untracking tuples has the desired effect of reducing GC overhead * Do not track most untrackable tuples during creation. This prevents large numbers of small tuples causing execessive GCs.
1 parent 4adf08a commit 0c01090

File tree

5 files changed

+93
-36
lines changed

5 files changed

+93
-36
lines changed

Include/internal/pycore_gc.h

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,12 @@ static inline void _PyGC_CLEAR_FINALIZED(PyObject *op) {
205205
#endif
206206
}
207207

208+
extern void _Py_ScheduleGC(PyThreadState *tstate);
209+
210+
#ifndef Py_GIL_DISABLED
211+
extern void _Py_TriggerGC(struct _gc_runtime_state *gcstate);
212+
#endif
213+
208214

209215
/* Tell the GC to track this object.
210216
*
@@ -238,14 +244,19 @@ static inline void _PyObject_GC_TRACK(
238244
"object is in generation which is garbage collected",
239245
filename, lineno, __func__);
240246

241-
PyInterpreterState *interp = _PyInterpreterState_GET();
242-
PyGC_Head *generation0 = &interp->gc.young.head;
247+
struct _gc_runtime_state *gcstate = &_PyInterpreterState_GET()->gc;
248+
PyGC_Head *generation0 = &gcstate->young.head;
243249
PyGC_Head *last = (PyGC_Head*)(generation0->_gc_prev);
244250
_PyGCHead_SET_NEXT(last, gc);
245251
_PyGCHead_SET_PREV(gc, last);
246-
uintptr_t not_visited = 1 ^ interp->gc.visited_space;
252+
uintptr_t not_visited = 1 ^ gcstate->visited_space;
247253
gc->_gc_next = ((uintptr_t)generation0) | not_visited;
248254
generation0->_gc_prev = (uintptr_t)gc;
255+
gcstate->young.count++; /* number of tracked GC objects */
256+
gcstate->heap_size++;
257+
if (gcstate->young.count > gcstate->young.threshold) {
258+
_Py_TriggerGC(gcstate);
259+
}
249260
#endif
250261
}
251262

@@ -280,6 +291,11 @@ static inline void _PyObject_GC_UNTRACK(
280291
_PyGCHead_SET_PREV(next, prev);
281292
gc->_gc_next = 0;
282293
gc->_gc_prev &= _PyGC_PREV_MASK_FINALIZED;
294+
struct _gc_runtime_state *gcstate = &_PyInterpreterState_GET()->gc;
295+
if (gcstate->young.count > 0) {
296+
gcstate->young.count--;
297+
}
298+
gcstate->heap_size--;
283299
#endif
284300
}
285301

@@ -343,7 +359,6 @@ extern PyObject *_PyGC_GetReferrers(PyInterpreterState *interp, PyObject *objs);
343359

344360
// Functions to clear types free lists
345361
extern void _PyGC_ClearAllFreeLists(PyInterpreterState *interp);
346-
extern void _Py_ScheduleGC(PyThreadState *tstate);
347362
extern void _Py_RunGC(PyThreadState *tstate);
348363

349364
union _PyStackRef;

Lib/test/test_gc.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1473,10 +1473,11 @@ def callback(ignored):
14731473
# The free-threaded build doesn't have multiple generations, so
14741474
# just trigger a GC manually.
14751475
gc.collect()
1476+
assert not detector.gc_happened
14761477
while not detector.gc_happened:
14771478
i += 1
1478-
if i > 10000:
1479-
self.fail("gc didn't happen after 10000 iterations")
1479+
if i > 100000:
1480+
self.fail("gc didn't happen after 100000 iterations")
14801481
self.assertEqual(len(ouch), 0)
14811482
junk.append([]) # this will eventually trigger gc
14821483

@@ -1548,8 +1549,8 @@ def __del__(self):
15481549
gc.collect()
15491550
while not detector.gc_happened:
15501551
i += 1
1551-
if i > 10000:
1552-
self.fail("gc didn't happen after 10000 iterations")
1552+
if i > 50000:
1553+
self.fail("gc didn't happen after 50000 iterations")
15531554
self.assertEqual(len(ouch), 0)
15541555
junk.append([]) # this will eventually trigger gc
15551556

@@ -1566,8 +1567,8 @@ def test_indirect_calls_with_gc_disabled(self):
15661567
detector = GC_Detector()
15671568
while not detector.gc_happened:
15681569
i += 1
1569-
if i > 10000:
1570-
self.fail("gc didn't happen after 10000 iterations")
1570+
if i > 100000:
1571+
self.fail("gc didn't happen after 100000 iterations")
15711572
junk.append([]) # this will eventually trigger gc
15721573

15731574
try:
@@ -1577,11 +1578,11 @@ def test_indirect_calls_with_gc_disabled(self):
15771578
detector = GC_Detector()
15781579
while not detector.gc_happened:
15791580
i += 1
1580-
if i > 10000:
1581+
if i > 100000:
15811582
break
15821583
junk.append([]) # this may eventually trigger gc (if it is enabled)
15831584

1584-
self.assertEqual(i, 10001)
1585+
self.assertEqual(i, 100001)
15851586
finally:
15861587
gc.enable()
15871588

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Fixes a regression in GC performance for a growing heap composed mostly of
2+
small tuples.
3+
4+
* Counts number of actually tracked objects, instead of trackable objects.
5+
This ensures that untracking tuples has the desired effect of reducing GC overhead.
6+
* Does not track most untrackable tuples during creation.
7+
This prevents large numbers of small tuples causing excessive GCs.

Objects/tupleobject.c

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,13 +156,26 @@ _PyTuple_MaybeUntrack(PyObject *op)
156156
_PyObject_GC_UNTRACK(op);
157157
}
158158

159+
/* Fast, but conservative check if an object maybe tracked
160+
May return true for an object that is not tracked,
161+
Will always return true for an object that is tracked.
162+
This is a temporary workaround until _PyObject_GC_IS_TRACKED
163+
becomes fast and safe to call on non-GC objects.
164+
*/
165+
static bool
166+
maybe_tracked(PyObject *ob)
167+
{
168+
return _PyType_IS_GC(Py_TYPE(ob));
169+
}
170+
159171
PyObject *
160172
PyTuple_Pack(Py_ssize_t n, ...)
161173
{
162174
Py_ssize_t i;
163175
PyObject *o;
164176
PyObject **items;
165177
va_list vargs;
178+
bool track = false;
166179

167180
if (n == 0) {
168181
return tuple_get_empty();
@@ -177,10 +190,15 @@ PyTuple_Pack(Py_ssize_t n, ...)
177190
items = result->ob_item;
178191
for (i = 0; i < n; i++) {
179192
o = va_arg(vargs, PyObject *);
193+
if (!track && maybe_tracked(o)) {
194+
track = true;
195+
}
180196
items[i] = Py_NewRef(o);
181197
}
182198
va_end(vargs);
183-
_PyObject_GC_TRACK(result);
199+
if (track) {
200+
_PyObject_GC_TRACK(result);
201+
}
184202
return (PyObject *)result;
185203
}
186204

@@ -377,11 +395,17 @@ PyTuple_FromArray(PyObject *const *src, Py_ssize_t n)
377395
return NULL;
378396
}
379397
PyObject **dst = tuple->ob_item;
398+
bool track = false;
380399
for (Py_ssize_t i = 0; i < n; i++) {
381400
PyObject *item = src[i];
401+
if (!track && maybe_tracked(item)) {
402+
track = true;
403+
}
382404
dst[i] = Py_NewRef(item);
383405
}
384-
_PyObject_GC_TRACK(tuple);
406+
if (track) {
407+
_PyObject_GC_TRACK(tuple);
408+
}
385409
return (PyObject *)tuple;
386410
}
387411

@@ -396,10 +420,17 @@ _PyTuple_FromStackRefStealOnSuccess(const _PyStackRef *src, Py_ssize_t n)
396420
return NULL;
397421
}
398422
PyObject **dst = tuple->ob_item;
423+
bool track = false;
399424
for (Py_ssize_t i = 0; i < n; i++) {
400-
dst[i] = PyStackRef_AsPyObjectSteal(src[i]);
425+
PyObject *item = PyStackRef_AsPyObjectSteal(src[i]);
426+
if (!track && maybe_tracked(item)) {
427+
track = true;
428+
}
429+
dst[i] = item;
430+
}
431+
if (track) {
432+
_PyObject_GC_TRACK(tuple);
401433
}
402-
_PyObject_GC_TRACK(tuple);
403434
return (PyObject *)tuple;
404435
}
405436

Python/gc.c

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1639,7 +1639,7 @@ assess_work_to_do(GCState *gcstate)
16391639
scale_factor = 2;
16401640
}
16411641
intptr_t new_objects = gcstate->young.count;
1642-
intptr_t max_heap_fraction = new_objects*3/2;
1642+
intptr_t max_heap_fraction = new_objects*2;
16431643
intptr_t heap_fraction = gcstate->heap_size / SCAN_RATE_DIVISOR / scale_factor;
16441644
if (heap_fraction > max_heap_fraction) {
16451645
heap_fraction = max_heap_fraction;
@@ -1654,6 +1654,9 @@ gc_collect_increment(PyThreadState *tstate, struct gc_collection_stats *stats)
16541654
GC_STAT_ADD(1, collections, 1);
16551655
GCState *gcstate = &tstate->interp->gc;
16561656
gcstate->work_to_do += assess_work_to_do(gcstate);
1657+
if (gcstate->work_to_do < 0) {
1658+
return;
1659+
}
16571660
untrack_tuples(&gcstate->young.head);
16581661
if (gcstate->phase == GC_PHASE_MARK) {
16591662
Py_ssize_t objects_marked = mark_at_start(tstate);
@@ -1696,7 +1699,6 @@ gc_collect_increment(PyThreadState *tstate, struct gc_collection_stats *stats)
16961699
gc_collect_region(tstate, &increment, &survivors, stats);
16971700
gc_list_merge(&survivors, visited);
16981701
assert(gc_list_is_empty(&increment));
1699-
gcstate->work_to_do += gcstate->heap_size / SCAN_RATE_DIVISOR / scale_factor;
17001702
gcstate->work_to_do -= increment_size;
17011703

17021704
add_stats(gcstate, 1, stats);
@@ -2299,28 +2301,29 @@ _Py_ScheduleGC(PyThreadState *tstate)
22992301
}
23002302

23012303
void
2302-
_PyObject_GC_Link(PyObject *op)
2304+
_Py_TriggerGC(struct _gc_runtime_state *gcstate)
23032305
{
2304-
PyGC_Head *gc = AS_GC(op);
2305-
// gc must be correctly aligned
2306-
_PyObject_ASSERT(op, ((uintptr_t)gc & (sizeof(uintptr_t)-1)) == 0);
2307-
23082306
PyThreadState *tstate = _PyThreadState_GET();
2309-
GCState *gcstate = &tstate->interp->gc;
2310-
gc->_gc_next = 0;
2311-
gc->_gc_prev = 0;
2312-
gcstate->young.count++; /* number of allocated GC objects */
2313-
gcstate->heap_size++;
2314-
if (gcstate->young.count > gcstate->young.threshold &&
2315-
gcstate->enabled &&
2316-
gcstate->young.threshold &&
2307+
if (gcstate->enabled &&
2308+
gcstate->young.threshold != 0 &&
23172309
!_Py_atomic_load_int_relaxed(&gcstate->collecting) &&
23182310
!_PyErr_Occurred(tstate))
23192311
{
23202312
_Py_ScheduleGC(tstate);
23212313
}
23222314
}
23232315

2316+
void
2317+
_PyObject_GC_Link(PyObject *op)
2318+
{
2319+
PyGC_Head *gc = AS_GC(op);
2320+
// gc must be correctly aligned
2321+
_PyObject_ASSERT(op, ((uintptr_t)gc & (sizeof(uintptr_t)-1)) == 0);
2322+
gc->_gc_next = 0;
2323+
gc->_gc_prev = 0;
2324+
2325+
}
2326+
23242327
void
23252328
_Py_RunGC(PyThreadState *tstate)
23262329
{
@@ -2427,6 +2430,11 @@ PyObject_GC_Del(void *op)
24272430
PyGC_Head *g = AS_GC(op);
24282431
if (_PyObject_GC_IS_TRACKED(op)) {
24292432
gc_list_remove(g);
2433+
GCState *gcstate = get_gc_state();
2434+
if (gcstate->young.count > 0) {
2435+
gcstate->young.count--;
2436+
}
2437+
gcstate->heap_size--;
24302438
#ifdef Py_DEBUG
24312439
PyObject *exc = PyErr_GetRaisedException();
24322440
if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0,
@@ -2440,11 +2448,6 @@ PyObject_GC_Del(void *op)
24402448
PyErr_SetRaisedException(exc);
24412449
#endif
24422450
}
2443-
GCState *gcstate = get_gc_state();
2444-
if (gcstate->young.count > 0) {
2445-
gcstate->young.count--;
2446-
}
2447-
gcstate->heap_size--;
24482451
PyObject_Free(((char *)op)-presize);
24492452
}
24502453

0 commit comments

Comments
 (0)