Skip to content

Commit 2e8d020

Browse files
committed
Fix major GC performance regression
* 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 5f357f3 commit 2e8d020

File tree

4 files changed

+86
-36
lines changed

4 files changed

+86
-36
lines changed

Include/internal/pycore_gc.h

Lines changed: 20 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,20 @@ 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+
PyThreadState *tstate = _PyThreadState_GET();
248+
struct _gc_runtime_state *gcstate = &tstate->interp->gc;
249+
PyGC_Head *generation0 = &gcstate->young.head;
243250
PyGC_Head *last = (PyGC_Head*)(generation0->_gc_prev);
244251
_PyGCHead_SET_NEXT(last, gc);
245252
_PyGCHead_SET_PREV(gc, last);
246-
uintptr_t not_visited = 1 ^ interp->gc.visited_space;
253+
uintptr_t not_visited = 1 ^ gcstate->visited_space;
247254
gc->_gc_next = ((uintptr_t)generation0) | not_visited;
248255
generation0->_gc_prev = (uintptr_t)gc;
256+
gcstate->young.count++; /* number of allocated GC objects */
257+
gcstate->heap_size++;
258+
if (gcstate->young.count > gcstate->young.threshold) {
259+
_Py_TriggerGC(gcstate);
260+
}
249261
#endif
250262
}
251263

@@ -280,6 +292,11 @@ static inline void _PyObject_GC_UNTRACK(
280292
_PyGCHead_SET_PREV(next, prev);
281293
gc->_gc_next = 0;
282294
gc->_gc_prev &= _PyGC_PREV_MASK_FINALIZED;
295+
struct _gc_runtime_state *gcstate = &_PyInterpreterState_GET()->gc;
296+
if (gcstate->young.count > 0) {
297+
gcstate->young.count--;
298+
}
299+
gcstate->heap_size--;
283300
#endif
284301
}
285302

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

344361
// Functions to clear types free lists
345362
extern void _PyGC_ClearAllFreeLists(PyInterpreterState *interp);
346-
extern void _Py_ScheduleGC(PyThreadState *tstate);
347363
extern void _Py_RunGC(PyThreadState *tstate);
348364

349365
union _PyStackRef;

Lib/test/test_gc.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1447,10 +1447,11 @@ def callback(ignored):
14471447
# The free-threaded build doesn't have multiple generations, so
14481448
# just trigger a GC manually.
14491449
gc.collect()
1450+
assert not detector.gc_happened
14501451
while not detector.gc_happened:
14511452
i += 1
1452-
if i > 10000:
1453-
self.fail("gc didn't happen after 10000 iterations")
1453+
if i > 50000:
1454+
self.fail("gc didn't happen after 50000 iterations")
14541455
self.assertEqual(len(ouch), 0)
14551456
junk.append([]) # this will eventually trigger gc
14561457

@@ -1522,8 +1523,8 @@ def __del__(self):
15221523
gc.collect()
15231524
while not detector.gc_happened:
15241525
i += 1
1525-
if i > 10000:
1526-
self.fail("gc didn't happen after 10000 iterations")
1526+
if i > 50000:
1527+
self.fail("gc didn't happen after 50000 iterations")
15271528
self.assertEqual(len(ouch), 0)
15281529
junk.append([]) # this will eventually trigger gc
15291530

@@ -1540,8 +1541,8 @@ def test_indirect_calls_with_gc_disabled(self):
15401541
detector = GC_Detector()
15411542
while not detector.gc_happened:
15421543
i += 1
1543-
if i > 10000:
1544-
self.fail("gc didn't happen after 10000 iterations")
1544+
if i > 50000:
1545+
self.fail("gc didn't happen after 50000 iterations")
15451546
junk.append([]) # this will eventually trigger gc
15461547

15471548
try:
@@ -1551,11 +1552,11 @@ def test_indirect_calls_with_gc_disabled(self):
15511552
detector = GC_Detector()
15521553
while not detector.gc_happened:
15531554
i += 1
1554-
if i > 10000:
1555+
if i > 50000:
15551556
break
15561557
junk.append([]) # this may eventually trigger gc (if it is enabled)
15571558

1558-
self.assertEqual(i, 10001)
1559+
self.assertEqual(i, 50001)
15591560
finally:
15601561
gc.enable()
15611562

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 alwys 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: 22 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);
@@ -2286,28 +2288,28 @@ _Py_ScheduleGC(PyThreadState *tstate)
22862288
}
22872289

22882290
void
2289-
_PyObject_GC_Link(PyObject *op)
2291+
_Py_TriggerGC(struct _gc_runtime_state *gcstate)
22902292
{
2291-
PyGC_Head *gc = AS_GC(op);
2292-
// gc must be correctly aligned
2293-
_PyObject_ASSERT(op, ((uintptr_t)gc & (sizeof(uintptr_t)-1)) == 0);
2294-
22952293
PyThreadState *tstate = _PyThreadState_GET();
2296-
GCState *gcstate = &tstate->interp->gc;
2297-
gc->_gc_next = 0;
2298-
gc->_gc_prev = 0;
2299-
gcstate->young.count++; /* number of allocated GC objects */
2300-
gcstate->heap_size++;
2301-
if (gcstate->young.count > gcstate->young.threshold &&
2302-
gcstate->enabled &&
2303-
gcstate->young.threshold &&
2294+
if (gcstate->enabled &&
23042295
!_Py_atomic_load_int_relaxed(&gcstate->collecting) &&
23052296
!_PyErr_Occurred(tstate))
23062297
{
23072298
_Py_ScheduleGC(tstate);
23082299
}
23092300
}
23102301

2302+
void
2303+
_PyObject_GC_Link(PyObject *op)
2304+
{
2305+
PyGC_Head *gc = AS_GC(op);
2306+
// gc must be correctly aligned
2307+
_PyObject_ASSERT(op, ((uintptr_t)gc & (sizeof(uintptr_t)-1)) == 0);
2308+
gc->_gc_next = 0;
2309+
gc->_gc_prev = 0;
2310+
2311+
}
2312+
23112313
void
23122314
_Py_RunGC(PyThreadState *tstate)
23132315
{
@@ -2414,6 +2416,11 @@ PyObject_GC_Del(void *op)
24142416
PyGC_Head *g = AS_GC(op);
24152417
if (_PyObject_GC_IS_TRACKED(op)) {
24162418
gc_list_remove(g);
2419+
GCState *gcstate = get_gc_state();
2420+
if (gcstate->young.count > 0) {
2421+
gcstate->young.count--;
2422+
}
2423+
gcstate->heap_size--;
24172424
#ifdef Py_DEBUG
24182425
PyObject *exc = PyErr_GetRaisedException();
24192426
if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0,
@@ -2427,11 +2434,6 @@ PyObject_GC_Del(void *op)
24272434
PyErr_SetRaisedException(exc);
24282435
#endif
24292436
}
2430-
GCState *gcstate = get_gc_state();
2431-
if (gcstate->young.count > 0) {
2432-
gcstate->young.count--;
2433-
}
2434-
gcstate->heap_size--;
24352437
PyObject_Free(((char *)op)-presize);
24362438
}
24372439

0 commit comments

Comments
 (0)