Skip to content

Commit 0c30b79

Browse files
committed
Expose a GC "duration" stat
1 parent b362632 commit 0c30b79

File tree

6 files changed

+60
-26
lines changed

6 files changed

+60
-26
lines changed

Doc/library/gc.rst

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,16 @@ The :mod:`gc` module provides the following functions:
108108

109109
* ``uncollectable`` is the total number of objects which were found
110110
to be uncollectable (and were therefore moved to the :data:`garbage`
111-
list) inside this generation.
111+
list) inside this generation;
112+
113+
* ``duration`` is the total time in seconds spent in collections for this
114+
generation.
112115

113116
.. versionadded:: 3.4
114117

118+
.. versionchanged:: 3.15
119+
Add ``duration``.
120+
115121

116122
.. function:: set_threshold(threshold0, [threshold1, [threshold2]])
117123

@@ -313,6 +319,9 @@ values but should not rebind them):
313319
"uncollectable": When *phase* is "stop", the number of objects
314320
that could not be collected and were put in :data:`garbage`.
315321

322+
"duration": When *phase* is "stop", the time in seconds spent in the
323+
collection.
324+
316325
Applications can add their own callbacks to this list. The primary
317326
use cases are:
318327

@@ -325,6 +334,9 @@ values but should not rebind them):
325334

326335
.. versionadded:: 3.3
327336

337+
.. versionchanged:: 3.14
338+
Add "duration".
339+
328340

329341
The following constants are provided for use with :func:`set_debug`:
330342

Include/internal/pycore_interp_structs.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,8 @@ struct gc_collection_stats {
179179
Py_ssize_t collected;
180180
/* total number of uncollectable objects (put into gc.garbage) */
181181
Py_ssize_t uncollectable;
182+
// Duration of the collection in seconds:
183+
double duration;
182184
};
183185

184186
/* Running stats per generation */
@@ -189,6 +191,8 @@ struct gc_generation_stats {
189191
Py_ssize_t collected;
190192
/* total number of uncollectable objects (put into gc.garbage) */
191193
Py_ssize_t uncollectable;
194+
// Duration of the collection in seconds:
195+
double duration;
192196
};
193197

194198
enum _GCPhase {

Lib/test/test_gc.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -847,10 +847,11 @@ def test_get_stats(self):
847847
for st in stats:
848848
self.assertIsInstance(st, dict)
849849
self.assertEqual(set(st),
850-
{"collected", "collections", "uncollectable"})
850+
{"collected", "collections", "uncollectable", "duration"})
851851
self.assertGreaterEqual(st["collected"], 0)
852852
self.assertGreaterEqual(st["collections"], 0)
853853
self.assertGreaterEqual(st["uncollectable"], 0)
854+
self.assertGreaterEqual(st["duration"], 0)
854855
# Check that collection counts are incremented correctly
855856
if gc.isenabled():
856857
self.addCleanup(gc.enable)
@@ -861,11 +862,19 @@ def test_get_stats(self):
861862
self.assertEqual(new[0]["collections"], old[0]["collections"] + 1)
862863
self.assertEqual(new[1]["collections"], old[1]["collections"])
863864
self.assertEqual(new[2]["collections"], old[2]["collections"])
865+
for stat in ["collected", "uncollectable", "duration"]:
866+
self.assertGreaterEqual(new[0][stat], old[0][stat])
867+
self.assertEqual(new[1][stat], old[1][stat])
868+
self.assertEqual(new[2][stat], old[2][stat])
864869
gc.collect(2)
865-
new = gc.get_stats()
866-
self.assertEqual(new[0]["collections"], old[0]["collections"] + 1)
870+
old, new = new, gc.get_stats()
871+
self.assertEqual(new[0]["collections"], old[0]["collections"])
867872
self.assertEqual(new[1]["collections"], old[1]["collections"])
868873
self.assertEqual(new[2]["collections"], old[2]["collections"] + 1)
874+
for stat in ["collected", "uncollectable", "duration"]:
875+
self.assertEqual(new[0][stat], old[0][stat])
876+
self.assertEqual(new[1][stat], old[1][stat])
877+
self.assertGreaterEqual(new[2][stat], old[2][stat])
869878

870879
def test_freeze(self):
871880
gc.freeze()
@@ -1298,9 +1307,10 @@ def test_collect(self):
12981307
# Check that we got the right info dict for all callbacks
12991308
for v in self.visit:
13001309
info = v[2]
1301-
self.assertTrue("generation" in info)
1302-
self.assertTrue("collected" in info)
1303-
self.assertTrue("uncollectable" in info)
1310+
self.assertIn("generation", info)
1311+
self.assertIn("collected", info)
1312+
self.assertIn("uncollectable", info)
1313+
self.assertIn("duration", info)
13041314

13051315
def test_collect_generation(self):
13061316
self.preclean()

Modules/gcmodule.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -358,10 +358,11 @@ gc_get_stats_impl(PyObject *module)
358358
for (i = 0; i < NUM_GENERATIONS; i++) {
359359
PyObject *dict;
360360
st = &stats[i];
361-
dict = Py_BuildValue("{snsnsn}",
361+
dict = Py_BuildValue("{snsnsnsd}",
362362
"collections", st->collections,
363363
"collected", st->collected,
364-
"uncollectable", st->uncollectable
364+
"uncollectable", st->uncollectable,
365+
"duration", st->duration
365366
);
366367
if (dict == NULL)
367368
goto error;

Python/gc.c

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1363,6 +1363,7 @@ gc_list_set_space(PyGC_Head *list, int space)
13631363
static void
13641364
add_stats(GCState *gcstate, int gen, struct gc_collection_stats *stats)
13651365
{
1366+
gcstate->generation_stats[gen].duration += stats->duration;
13661367
gcstate->generation_stats[gen].collected += stats->collected;
13671368
gcstate->generation_stats[gen].uncollectable += stats->uncollectable;
13681369
gcstate->generation_stats[gen].collections += 1;
@@ -1383,6 +1384,7 @@ gc_collect_young(PyThreadState *tstate,
13831384
gc_list_init(&survivors);
13841385
gc_list_set_space(young, gcstate->visited_space);
13851386
gc_collect_region(tstate, young, &survivors, stats);
1387+
stats->visited += gcstate->young.count;
13861388
gc_list_merge(&survivors, visited);
13871389
validate_spaces(gcstate);
13881390
gcstate->young.count = 0;
@@ -1697,6 +1699,7 @@ gc_collect_increment(PyThreadState *tstate, struct gc_collection_stats *stats)
16971699
PyGC_Head survivors;
16981700
gc_list_init(&survivors);
16991701
gc_collect_region(tstate, &increment, &survivors, stats);
1702+
stats->visited += increment_size;
17001703
gc_list_merge(&survivors, visited);
17011704
assert(gc_list_is_empty(&increment));
17021705
gcstate->work_to_do -= increment_size;
@@ -1729,6 +1732,7 @@ gc_collect_full(PyThreadState *tstate,
17291732

17301733
gc_collect_region(tstate, visited, visited,
17311734
stats);
1735+
stats->visited += gcstate->young.count + gcstate->old[0].count + gcstate->old[1].count;
17321736
validate_spaces(gcstate);
17331737
gcstate->young.count = 0;
17341738
gcstate->old[0].count = 0;
@@ -1846,10 +1850,11 @@ do_gc_callback(GCState *gcstate, const char *phase,
18461850
assert(PyList_CheckExact(gcstate->callbacks));
18471851
PyObject *info = NULL;
18481852
if (PyList_GET_SIZE(gcstate->callbacks) != 0) {
1849-
info = Py_BuildValue("{sisnsn}",
1853+
info = Py_BuildValue("{sisnsnsd}",
18501854
"generation", generation,
18511855
"collected", stats->collected,
1852-
"uncollectable", stats->uncollectable);
1856+
"uncollectable", stats->uncollectable,
1857+
"duration", stats->duration);
18531858
if (info == NULL) {
18541859
PyErr_FormatUnraisable("Exception ignored while invoking gc callbacks");
18551860
return;
@@ -2080,15 +2085,15 @@ _PyGC_Collect(PyThreadState *tstate, int generation, _PyGC_Reason reason)
20802085
if (reason != _Py_GC_REASON_SHUTDOWN) {
20812086
invoke_gc_callback(gcstate, "start", generation, &stats);
20822087
}
2083-
PyTime_t t1;
20842088
if (gcstate->debug & _PyGC_DEBUG_STATS) {
20852089
PySys_WriteStderr("gc: collecting generation %d...\n", generation);
2086-
(void)PyTime_PerfCounterRaw(&t1);
20872090
show_stats_each_generations(gcstate);
20882091
}
20892092
if (PyDTrace_GC_START_ENABLED()) {
20902093
PyDTrace_GC_START(generation);
20912094
}
2095+
PyTime_t start, stop;
2096+
(void)PyTime_PerfCounterRaw(&start);
20922097
PyObject *exc = _PyErr_GetRaisedException(tstate);
20932098
switch(generation) {
20942099
case 0:
@@ -2103,6 +2108,8 @@ _PyGC_Collect(PyThreadState *tstate, int generation, _PyGC_Reason reason)
21032108
default:
21042109
Py_UNREACHABLE();
21052110
}
2111+
(void)PyTime_PerfCounterRaw(&stop);
2112+
stats.duration = PyTime_AsSecondsDouble(stop - start);
21062113
if (PyDTrace_GC_DONE_ENABLED()) {
21072114
PyDTrace_GC_DONE(stats.uncollectable + stats.collected);
21082115
}
@@ -2124,12 +2131,9 @@ _PyGC_Collect(PyThreadState *tstate, int generation, _PyGC_Reason reason)
21242131
_Py_atomic_store_int(&gcstate->collecting, 0);
21252132

21262133
if (gcstate->debug & _PyGC_DEBUG_STATS) {
2127-
PyTime_t t2;
2128-
(void)PyTime_PerfCounterRaw(&t2);
2129-
double d = PyTime_AsSecondsDouble(t2 - t1);
21302134
PySys_WriteStderr(
21312135
"gc: done, %zd unreachable, %zd uncollectable, %.4fs elapsed\n",
2132-
stats.collected + stats.uncollectable, stats.uncollectable, d
2136+
stats.collected + stats.uncollectable, stats.uncollectable, stats.duration
21332137
);
21342138
}
21352139

Python/gc_free_threading.c

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1911,7 +1911,7 @@ handle_resurrected_objects(struct collection_state *state)
19111911
static void
19121912
invoke_gc_callback(PyThreadState *tstate, const char *phase,
19131913
int generation, Py_ssize_t collected,
1914-
Py_ssize_t uncollectable)
1914+
Py_ssize_t uncollectable, double duration)
19151915
{
19161916
assert(!_PyErr_Occurred(tstate));
19171917

@@ -1928,7 +1928,8 @@ invoke_gc_callback(PyThreadState *tstate, const char *phase,
19281928
info = Py_BuildValue("{sisnsn}",
19291929
"generation", generation,
19301930
"collected", collected,
1931-
"uncollectable", uncollectable);
1931+
"uncollectable", uncollectable,
1932+
"duration", duration);
19321933
if (info == NULL) {
19331934
PyErr_FormatUnraisable("Exception ignored while "
19341935
"invoking gc callbacks");
@@ -2340,7 +2341,6 @@ gc_collect_main(PyThreadState *tstate, int generation, _PyGC_Reason reason)
23402341
{
23412342
Py_ssize_t m = 0; /* # objects collected */
23422343
Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
2343-
PyTime_t t1 = 0; /* initialize to prevent a compiler warning */
23442344
GCState *gcstate = &tstate->interp->gc;
23452345

23462346
// gc_collect_main() must not be called before _PyGC_Init
@@ -2372,7 +2372,7 @@ gc_collect_main(PyThreadState *tstate, int generation, _PyGC_Reason reason)
23722372
GC_STAT_ADD(generation, collections, 1);
23732373

23742374
if (reason != _Py_GC_REASON_SHUTDOWN) {
2375-
invoke_gc_callback(tstate, "start", generation, 0, 0);
2375+
invoke_gc_callback(tstate, "start", generation, 0, 0, 0);
23762376
}
23772377

23782378
if (gcstate->debug & _PyGC_DEBUG_STATS) {
@@ -2385,6 +2385,8 @@ gc_collect_main(PyThreadState *tstate, int generation, _PyGC_Reason reason)
23852385
if (PyDTrace_GC_START_ENABLED()) {
23862386
PyDTrace_GC_START(generation);
23872387
}
2388+
PyTime_t start, stop;
2389+
(void)PyTime_PerfCounterRaw(&start);
23882390

23892391
PyInterpreterState *interp = tstate->interp;
23902392

@@ -2399,13 +2401,13 @@ gc_collect_main(PyThreadState *tstate, int generation, _PyGC_Reason reason)
23992401
m = state.collected;
24002402
n = state.uncollectable;
24012403

2404+
(void)PyTime_PerfCounterRaw(&stop);
2405+
double duration = PyTime_AsSecondsDouble(stop - start);
2406+
24022407
if (gcstate->debug & _PyGC_DEBUG_STATS) {
2403-
PyTime_t t2;
2404-
(void)PyTime_PerfCounterRaw(&t2);
2405-
double d = PyTime_AsSecondsDouble(t2 - t1);
24062408
PySys_WriteStderr(
24072409
"gc: done, %zd unreachable, %zd uncollectable, %.4fs elapsed\n",
2408-
n+m, n, d);
2410+
n+m, n, duration);
24092411
}
24102412

24112413
// Clear the current thread's free-list again.
@@ -2426,6 +2428,7 @@ gc_collect_main(PyThreadState *tstate, int generation, _PyGC_Reason reason)
24262428
stats->collections++;
24272429
stats->collected += m;
24282430
stats->uncollectable += n;
2431+
stats->duration += duration;
24292432

24302433
GC_STAT_ADD(generation, objects_collected, m);
24312434
#ifdef Py_STATS
@@ -2444,7 +2447,7 @@ gc_collect_main(PyThreadState *tstate, int generation, _PyGC_Reason reason)
24442447
}
24452448

24462449
if (reason != _Py_GC_REASON_SHUTDOWN) {
2447-
invoke_gc_callback(tstate, "stop", generation, m, n);
2450+
invoke_gc_callback(tstate, "stop", generation, m, n, duration);
24482451
}
24492452

24502453
assert(!_PyErr_Occurred(tstate));

0 commit comments

Comments
 (0)