Debian Codegraph @

pyinstrument/low_level/stat_profile.c

raw symbols SCIP
1 #include <Python.h>
2 #include <structmember.h>
3 #include <frameobject.h>
4
5 #include "pyi_floatclock.h"
6 #include "pyi_timing_thread.h"
7 #include <float.h>
8
9 ////////////////////////////
10 // Version/Platform shims //
11 ////////////////////////////
12
13 /* Python 2 shim */
14 #if PY_MAJOR_VERSION < 3
15
16 #define PyUnicode_InternFromString PyString_InternFromString
17
18 #endif
19
20 #if PY_VERSION_HEX >= 0x030b0000 // Python 3.11.0
21 #define PyFrame_GETBACK(f) PyFrame_GetBack(f)
22 #else
23 static PyFrameObject *
24 _PyFrame_GetBack(PyFrameObject *frame) {
25 Py_XINCREF(frame->f_back);
26 return frame->f_back;
27 }
28 #define PyFrame_GETBACK(f) _PyFrame_GetBack(f)
29 #endif
30
31 ///////////////////
32 // ProfilerState //
33 ///////////////////
34
35 typedef struct profiler_state {
36 PyObject_HEAD
37 PyObject *target;
38 double interval;
39 double last_invocation;
40 PyObject *context_var;
41 PyObject *last_context_var_value;
42 PyObject *await_stack_list;
43 PyObject *timer_func;
44 int timer_thread_subscription_id;
45 PYIFloatClockType floatclock_type;
46 } ProfilerState;
47
48 static void ProfilerState_SetTarget(ProfilerState *self, PyObject *target) {
49 PyObject *tmp = self->target;
50 Py_XINCREF(target);
51 self->target = target;
52 Py_XDECREF(tmp);
53 }
54
55 /**
56 * Updates last_context_var_value.
57 *
58 * Returns true on success, sets an exception and returns false on failure.
59 * */
60 static int ProfilerState_UpdateContextVar(ProfilerState *self) {
61 PyObject *old = self->last_context_var_value;
62 PyObject *new = NULL;
63 int status = PyContextVar_Get(self->context_var, NULL, &new);
64 if (status == -1) {
65 PyErr_SetString(PyExc_Exception, "failed to get value of the context var");
66 return 0;
67 }
68
69 if (old == new) {
70 // The object is the same, so we don't need the new reference.
71 Py_DECREF(new);
72 return 1;
73 }
74
75 self->last_context_var_value = new;
76
77 Py_XDECREF(old);
78
79 return 1;
80 }
81
82 /**
83 * Returns the current time for this profiler. On error, returns -1.0.
84 */
85 static double ProfilerState_GetTime(ProfilerState *self) {
86 if (self->timer_func != NULL) {
87 // when a self->timer_func is set, call that.
88 #if PY_VERSION_HEX >= 0x03090000
89 PyObject *result = PyObject_CallNoArgs(self->timer_func);
90 #else
91 PyObject *result = PyObject_CallObject(self->timer_func, NULL);
92 #endif
93 if (result == NULL) {
94 return -1.0;
95 }
96
97 if (!PyFloat_Check(result)) {
98 PyErr_SetString(PyExc_RuntimeError, "custom time function must return a float");
99 return -1.0;
100 }
101
102 double resultDouble = PyFloat_AsDouble(result);
103
104 Py_DECREF(result);
105 return resultDouble;
106 } else if (self->timer_thread_subscription_id >= 0) {
107 // when a self->timer_thread_subscription_id is set, use the timing thread.
108 return pyi_timing_thread_get_time();
109 } else {
110 // otherwise as normal, call the synchronous C timer function.
111 return pyi_floatclock(self->floatclock_type);
112 }
113 }
114
115 static void ProfilerState_Dealloc(ProfilerState *self) {
116 ProfilerState_SetTarget(self, NULL);
117 Py_XDECREF(self->context_var);
118 Py_XDECREF(self->last_context_var_value);
119 Py_XDECREF(self->await_stack_list);
120 Py_XDECREF(self->timer_func);
121 if (self->timer_thread_subscription_id >= 0) {
122 pyi_timing_thread_unsubscribe(self->timer_thread_subscription_id);
123 }
124 Py_TYPE(self)->tp_free(self);
125 }
126
127 static PyTypeObject ProfilerState_Type = {
128 PyVarObject_HEAD_INIT(NULL, 0)
129 "pyinstrument.stat_profile.ProfilerState", /* tp_name */
130 sizeof(ProfilerState), /* tp_basicsize */
131 0, /* tp_itemsize */
132 (destructor)ProfilerState_Dealloc, /* tp_dealloc */
133 0, /* tp_print */
134 0, /* tp_getattr */
135 0, /* tp_setattr */
136 0, /* tp_reserved */
137 0, /* tp_repr */
138 0, /* tp_as_number */
139 0, /* tp_as_sequence */
140 0, /* tp_as_mapping */
141 0, /* tp_hash */
142 0, /* tp_call */
143 0, /* tp_str */
144 0, /* tp_getattro */
145 0, /* tp_setattro */
146 0, /* tp_as_buffer */
147 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
148 0, /* tp_doc */
149 0, /* tp_traverse */
150 0, /* tp_clear */
151 0, /* tp_richcompare */
152 0, /* tp_weaklistoffset */
153 0, /* tp_iter */
154 0, /* tp_iternext */
155 0, /* tp_methods */
156 0, /* tp_members */
157 0, /* tp_getset */
158 0, /* tp_base */
159 0, /* tp_dict */
160 0, /* tp_descr_get */
161 0, /* tp_descr_set */
162 0, /* tp_dictoffset */
163 0, /* tp_init */
164 PyType_GenericAlloc, /* tp_alloc */
165 PyType_GenericNew, /* tp_new */
166 PyObject_Del, /* tp_free */
167 };
168
169 static ProfilerState *ProfilerState_New(void) {
170 ProfilerState *op = PyObject_New(ProfilerState, &ProfilerState_Type);
171 op->target = NULL;
172 op->interval = 0.0;
173 op->last_invocation = 0.0;
174 op->context_var = NULL;
175 op->last_context_var_value = NULL;
176 op->await_stack_list = PyList_New(0);
177 op->timer_func = NULL;
178 op->timer_thread_subscription_id = -1;
179 op->floatclock_type = PYI_FLOATCLOCK_DEFAULT;
180 return op;
181 }
182
183 ////////////////////////
184 // Internal functions //
185 ////////////////////////
186
187 static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
188
189 static PyObject *SELF_STRING = NULL;
190 static PyObject *CLS_STRING = NULL;
191 static PyObject *TRACEBACKHIDE_STRING = NULL;
192
193 #define TIMER_TYPE_WALLTIME 0
194 #define TIMER_TYPE_WALLTIME_THREAD 1
195 #define TIMER_TYPE_TIMER_FUNC 2
196 #define TIMER_TYPE_WALLTIME_COARSE 3
197
198 #define WHAT_CALL 0
199 #define WHAT_EXCEPTION 1
200 #define WHAT_LINE 2
201 #define WHAT_RETURN 3
202 #define WHAT_C_CALL 4
203 #define WHAT_C_EXCEPTION 5
204 #define WHAT_C_RETURN 6
205 #define WHAT_CONTEXT_CHANGED 7
206
207 static int
208 stat_profile_init(void)
209 {
210 static char *whatnames[8] = {"call", "exception", "line", "return",
211 "c_call", "c_exception", "c_return",
212 "context_changed"};
213 PyObject *name;
214 int i;
215 for (i = 0; i < 8; ++i) {
216 if (whatstrings[i] == NULL) {
217 name = PyUnicode_InternFromString(whatnames[i]);
218 if (name == NULL)
219 return -1;
220 whatstrings[i] = name;
221 }
222 }
223
224 SELF_STRING = PyUnicode_InternFromString("self");
225 if (SELF_STRING == NULL) return -1;
226
227 CLS_STRING = PyUnicode_InternFromString("cls");
228 if (CLS_STRING == NULL) return -1;
229
230 TRACEBACKHIDE_STRING = PyUnicode_InternFromString("__tracebackhide__");
231 if (TRACEBACKHIDE_STRING == NULL) return -1;
232
233 return 0;
234 }
235
236 static PyObject *
237 call_target(ProfilerState *pState, PyFrameObject *frame, int what, PyObject *arg)
238 {
239 // note: we no longer call PyFrame_FastToLocals and PyFrame_LocalsToFast
240 // here, as it's only needed for python-level modification of locals,
241 // which a profiler doesn't need to do.
242
243 #if PY_VERSION_HEX >= 0x03090000
244 // vectorcall implementation could be faster, is available in Python 3.9
245 PyObject *callargs[4] = { NULL, (PyObject *) frame, whatstrings[what], arg == NULL ? Py_None : arg };
246 PyObject *result = PyObject_Vectorcall(pState->target, callargs + 1, 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL);
247 #else
248 PyObject *result = PyObject_CallFunctionObjArgs(pState->target, (PyObject *) frame, whatstrings[what], arg == NULL ? Py_None : arg, NULL);
249 #endif
250
251 if (result == NULL) {
252 PyTraceBack_Here(frame);
253 }
254
255 return result;
256 }
257
258 /**
259 * Returns a new reference to a PyCodeObject for the given frame.
260 */
261 static PyCodeObject *
262 code_from_frame(PyFrameObject* frame)
263 {
264 #if PY_VERSION_HEX >= 0x03090000
265 return PyFrame_GetCode(frame);
266 #else
267 PyCodeObject *result = frame->f_code;
268 Py_XINCREF(result);
269 return result;
270 #endif
271 }
272
273 /**
274 * Returns a new reference to a PyTupleObject containing the names of the
275 * local variables.
276 */
277 static PyObject *
278 local_names_from_code(PyCodeObject *code)
279 {
280 #if PY_VERSION_HEX >= 0x030b0000
281 return PyCode_GetVarnames(code);
282 #else
283 PyObject *result = code->co_varnames;
284 Py_XINCREF(result);
285 return result;
286 #endif
287 }
288
289 #if PY_VERSION_HEX >= 0x030b0000 // Python 3.11.0
290 /**
291 * Returns a C-string containing the name of the class in the frame. The
292 * memory belongs to the type object, so it should not be freed.
293 */
294 static const char *
295 _get_class_name_of_frame(PyFrameObject *frame, PyCodeObject *code) {
296 PyObject *localsNames = PyCode_GetVarnames(code);
297
298 if (localsNames == NULL) {
299 return NULL;
300 }
301
302 PyObject *firstArgName = PyTuple_GET_ITEM(localsNames, 0);
303
304 if (firstArgName == NULL) {
305 Py_DECREF(localsNames);
306 return NULL;
307 }
308
309 int has_self = PyUnicode_Compare(firstArgName, SELF_STRING) == 0;
310 int has_cls = PyUnicode_Compare(firstArgName, CLS_STRING) == 0;
311
312 Py_DECREF(localsNames);
313
314 if (!has_self && !has_cls) {
315 // PyFrame_GetLocals is expensive and changes the frame, so we don't
316 // want to call it unless we have to.
317 return NULL;
318 }
319
320 const char *result = NULL;
321
322 PyObject *locals = PyFrame_GetLocals(frame);
323
324 if (!PyMapping_Check(locals)) {
325 Py_DECREF(locals);
326 return NULL;
327 }
328
329 // we still have to check the locals has the key, because it could have
330 // been "del'd"
331 if (has_self && PyMapping_HasKey(locals, SELF_STRING)) {
332 PyObject *self = PyObject_GetItem(locals, SELF_STRING);
333
334 if (!self) {
335 PyErr_Clear();
336 Py_DECREF(locals);
337 return NULL;
338 }
339
340 result = _PyType_Name(self->ob_type);
341 Py_DECREF(self);
342 }
343 else if (has_cls && PyMapping_HasKey(locals, CLS_STRING)) {
344 PyObject *cls = PyObject_GetItem(locals, CLS_STRING);
345
346 if (!cls) {
347 PyErr_Clear();
348 Py_DECREF(locals);
349 return NULL;
350 }
351
352 if (PyType_Check(cls)) {
353 PyTypeObject *type = (PyTypeObject *)cls;
354 result = _PyType_Name(type);
355 }
356 Py_DECREF(cls);
357 }
358
359 Py_DECREF(locals);
360 return result;
361 }
362
363 #else
364
365 static PyObject *
366 _get_first_arg_from_cell_variables(PyFrameObject *frame, PyCodeObject *code) {
367 if (!code->co_cell2arg) {
368 // we don't have args in cell variables
369 return NULL;
370 }
371
372 Py_ssize_t ncells = PyTuple_GET_SIZE(code->co_cellvars);
373
374 for (int i = 0; i < ncells; i++) {
375 if (code->co_cell2arg[i] == CO_CELL_NOT_AN_ARG) {
376 // this cell is not an argument
377 continue;
378 }
379
380 // get the cell value
381 // the cells are after the local variables
382 PyObject *cell = frame->f_localsplus[code->co_nlocals + i];
383
384 // return the value inside the cell
385 if (!PyCell_Check(cell)) {
386 continue;
387 }
388
389 return PyCell_GET(cell);
390 }
391
392 // cell variable not found
393 return NULL;
394 }
395
396 static const char *
397 _get_class_name_of_frame(PyFrameObject *frame, PyCodeObject *code) {
398 // This code looks only at the first 'fast' frame local.
399 //
400 // A generalisable way to get a local variable would be to look at every
401 // local for one with the name 'self' or 'cls'. And such a general method
402 // should also prefer f_locals, if it exists.
403 //
404 // But, function args are always be the first locals, self/cls is always
405 // be the first arg, and f_localsplus is always set, even if f_locals
406 // exists. So we only look at the first f_localsplus entry.
407
408 if (code->co_argcount < 1) {
409 return NULL;
410 }
411
412 if (!PyTuple_Check(code->co_varnames)) {
413 // co_varnames must be a tuple
414 return NULL;
415 }
416
417 if (code->co_nlocals < 1 || PyTuple_Size(code->co_varnames) < 1) {
418 return NULL;
419 }
420
421 PyObject *first_var_name = PyTuple_GetItem(code->co_varnames, 0);
422 int first_var_is_self = (PyUnicode_Compare(first_var_name, SELF_STRING) == 0);
423 int first_var_is_cls = (PyUnicode_Compare(first_var_name, CLS_STRING) == 0);
424
425 if (!(first_var_is_self || first_var_is_cls)) {
426 return NULL;
427 }
428
429 PyObject *first_var = frame->f_localsplus[0];
430
431 if (first_var == NULL) {
432 // Sometimes arguments are in cells, if they're accessible from other
433 // scopes, for example an inner function that captures self. In that
434 // case, the local var is NULL, and it's stored as a cell instead.
435 first_var = _get_first_arg_from_cell_variables(frame, code);
436 }
437
438 if (first_var == NULL) {
439 // not sure why this would happen, but as a failsafe.
440 return NULL;
441 }
442
443 if (first_var_is_self) {
444 PyTypeObject *type = first_var->ob_type;
445 return _PyType_Name(type);
446 } else if (first_var_is_cls) {
447 if (!PyType_Check(first_var)) {
448 return NULL;
449 }
450 PyTypeObject *type = (PyTypeObject *)first_var;
451 return _PyType_Name(type);
452 } else {
453 Py_FatalError("unreachable code");
454 }
455
456 return NULL;
457 }
458
459 #endif
460
461
462 /**
463 * returns `1` if any variable named `"__trackbackhide__"` is defined in frame
464 * locals, returns `0` otherwise
465 */
466 static const int
467 _get_tracebackhide(PyFrameObject *frame, PyCodeObject *code) {
468 PyObject *locals_names = local_names_from_code(code);
469
470 if (locals_names == NULL) {
471 return 0;
472 }
473
474 if (!PySequence_Check(locals_names)) {
475 // locals_names must be a sequence
476 Py_DECREF(locals_names);
477 return 0;
478 }
479
480 int tracebackhide = PySequence_Contains(locals_names, TRACEBACKHIDE_STRING);
481
482 Py_DECREF(locals_names);
483
484 if (tracebackhide < 0) {
485 // in this case the PySequence_Contains function encountered an error
486 Py_FatalError("could not determine names of frame local variables");
487 } else {
488 return tracebackhide;
489 }
490 }
491
492 /**
493 * Returns a new reference to pyinstrument's frame info string for the given frame.
494 */
495 static PyObject *
496 _get_frame_info(PyFrameObject *frame) {
497 PyCodeObject *code = code_from_frame(frame);
498
499 PyObject *class_name_attribute;
500
501 const char *class_name = _get_class_name_of_frame(frame, code);
502 if (class_name == NULL) {
503 class_name_attribute = PyUnicode_New(0, 127); // empty string
504 } else {
505 class_name_attribute = PyUnicode_FromFormat(
506 "%c%c%s",
507 1, // 0x01 char denotes 'attribute'
508 'c', // 'c' char denotes 'class name'
509 class_name
510 );
511 }
512
513 PyObject *line_number_attribute;
514
515 int line_number = PyFrame_GetLineNumber(frame);
516 if (line_number < 1) {
517 line_number_attribute = PyUnicode_New(0, 127);
518 } else {
519 line_number_attribute = PyUnicode_FromFormat(
520 "%c%c%d",
521 1,
522 'l', // 'l' char denotes 'line number'
523 line_number
524 );
525 }
526
527 PyObject *frame_hidden_attribute;
528
529 int tracebackhide = _get_tracebackhide(frame, code);
530 if (tracebackhide <= 0) {
531 frame_hidden_attribute = PyUnicode_New(0, 127);
532 } else {
533 frame_hidden_attribute = PyUnicode_FromFormat(
534 "%c%c%c",
535 1,
536 'h', // 'h' char denotes 'frame hidden'
537 '1' // '1' char denotes 'true'
538 );
539 }
540
541 PyObject *result = PyUnicode_FromFormat(
542 "%U%c%U%c%i%U%U%U",
543 code->co_name,
544 0, // NULL char
545 code->co_filename,
546 0, // NULL char
547 code->co_firstlineno,
548 class_name_attribute,
549 line_number_attribute,
550 frame_hidden_attribute
551 );
552
553 Py_DECREF(code);
554 Py_DECREF(class_name_attribute);
555 Py_DECREF(line_number_attribute);
556 Py_DECREF(frame_hidden_attribute);
557
558 return result;
559 }
560
561 static int
562 _parse_timer_type(PyObject *timer_type, int defaultValue) {
563 if (timer_type == NULL || timer_type == Py_None) {
564 return defaultValue;
565 }
566
567 if (!PyUnicode_Check(timer_type)) {
568 PyErr_SetString(PyExc_TypeError, "timer_type must be a string");
569 return -1;
570 }
571
572 if (PyUnicode_CompareWithASCIIString(timer_type, "walltime") == 0) {
573 return TIMER_TYPE_WALLTIME;
574 } else if (PyUnicode_CompareWithASCIIString(timer_type, "walltime_thread") == 0) {
575 return TIMER_TYPE_WALLTIME_THREAD;
576 } else if (PyUnicode_CompareWithASCIIString(timer_type, "timer_func") == 0) {
577 return TIMER_TYPE_TIMER_FUNC;
578 } else if (PyUnicode_CompareWithASCIIString(timer_type, "walltime_coarse") == 0) {
579 return TIMER_TYPE_WALLTIME_COARSE;
580 } else {
581 PyErr_SetString(PyExc_TypeError, "timer_type must be 'walltime', 'walltime_thread', 'walltime_coarse', or 'timer_func'");
582 return -1;
583 }
584 }
585
586 //////////////////////
587 // Public functions //
588 //////////////////////
589
590 /**
591 * The profile function. Passed to PyEval_SetProfile, and called with
592 * function frames as the program executes by Python
593 */
594 static int
595 profile(PyObject *op, PyFrameObject *frame, int what, PyObject *arg)
596 {
597 ProfilerState *pState = (ProfilerState *)op;
598 PyObject *result;
599
600 double now = ProfilerState_GetTime(pState);
601 if (now == -1.0) {
602 PyEval_SetProfile(NULL, NULL);
603 return -1;
604 }
605
606 // check for context var change, send context_changed event if seen
607 if (pState->context_var) {
608 PyObject *old_context_var_value = pState->last_context_var_value;
609 Py_XINCREF(old_context_var_value);
610
611 if (!ProfilerState_UpdateContextVar(pState)) {
612 PyEval_SetProfile(NULL, NULL);
613 return -1;
614 }
615
616 if (old_context_var_value != pState->last_context_var_value) {
617 PyFrameObject *context_change_frame; // borrowed reference
618 PyFrameObject *parent_frame = PyFrame_GETBACK(frame); // strong reference, maybe null
619
620 if (what == WHAT_CALL && parent_frame) {
621 context_change_frame = parent_frame;
622 } else {
623 context_change_frame = frame;
624 }
625
626 PyObject *context_change_arg = PyTuple_Pack(
627 3,
628 pState->last_context_var_value,
629 old_context_var_value,
630 pState->await_stack_list
631 );
632
633 result = call_target(pState, context_change_frame, WHAT_CONTEXT_CHANGED, context_change_arg);
634
635 Py_DECREF(context_change_arg);
636 Py_XDECREF(parent_frame);
637
638 if (result == NULL) {
639 PyEval_SetProfile(NULL, NULL);
640 return -1;
641 }
642
643 Py_DECREF(result);
644 }
645
646 Py_XDECREF(old_context_var_value);
647 }
648
649 // if we're returning from a coroutine, add that to the await stack
650 PyCodeObject* code = code_from_frame(frame);
651
652 if ((what == WHAT_RETURN) && (code->co_flags & 0x80)) {
653 PyObject *frame_identifier = _get_frame_info(frame);
654
655 int status = PyList_Append(pState->await_stack_list, frame_identifier);
656 Py_DECREF(frame_identifier);
657 Py_DECREF(code);
658
659 if (status == -1) {
660 PyEval_SetProfile(NULL, NULL);
661 return -1;
662 }
663 } else {
664 Py_DECREF(code);
665
666 // clear the list
667 int status = PyList_SetSlice(
668 pState->await_stack_list,
669 0,
670 PyList_GET_SIZE(pState->await_stack_list),
671 NULL
672 );
673
674 if (status == -1) {
675 PyEval_SetProfile(NULL, NULL);
676 return -1;
677 }
678 }
679
680
681 // stat profile
682 if (now < pState->last_invocation + pState->interval) {
683 return 0;
684 }
685
686 pState->last_invocation = now;
687 result = call_target(pState, frame, what, arg);
688
689 if (result == NULL) {
690 PyEval_SetProfile(NULL, NULL);
691 return -1;
692 }
693
694 Py_DECREF(result);
695 return 0;
696 }
697
698 /**
699 * The 'setprofile' function. This is the public API that can be called
700 * from Python code.
701 */
702 static PyObject *
703 setstatprofile(PyObject *m, PyObject *args, PyObject *kwds)
704 {
705 static char *kwlist[] = {"target", "interval", "context_var", "timer_type", "timer_func", NULL};
706 ProfilerState *pState = NULL;
707 double interval = 0.0;
708 PyObject *target = NULL;
709 PyObject *context_var = NULL;
710 PyObject *timer_type = NULL;
711 PyObject *timer_func = NULL;
712
713 if (! PyArg_ParseTupleAndKeywords(args, kwds, "O|dO!UO", kwlist, &target, &interval, &PyContextVar_Type, &context_var, &timer_type, &timer_func))
714 return NULL;
715
716 if (target == Py_None) {
717 target = NULL;
718 }
719
720 if (target) {
721 if (!PyCallable_Check(target)) {
722 PyErr_SetString(PyExc_TypeError, "target must be callable");
723 return NULL;
724 }
725
726 pState = ProfilerState_New();
727 if (pState == NULL) { // Check if allocation failed
728 return NULL;
729 }
730
731 ProfilerState_SetTarget(pState, target);
732
733 // default interval is 1 ms
734 pState->interval = (interval > 0) ? interval : 0.001;
735
736 int timer_type_int = _parse_timer_type(timer_type, TIMER_TYPE_WALLTIME);
737 if (timer_type_int == -1) {
738 goto error;
739 }
740
741 if (timer_func == Py_None) {
742 timer_func = NULL;
743 }
744
745 if (timer_type_int == TIMER_TYPE_TIMER_FUNC && timer_func == NULL) {
746 PyErr_SetString(PyExc_TypeError, "timer_func must be set if timer_type is 'timer_func'");
747 goto error;
748 }
749
750 if (timer_func && timer_type_int != TIMER_TYPE_TIMER_FUNC) {
751 PyErr_SetString(PyExc_TypeError, "timer_type must be 'timer_func' if timer_func is set");
752 goto error;
753 }
754
755 if (timer_func) {
756 Py_INCREF(timer_func);
757 pState->timer_func = timer_func;
758 } else if (timer_type_int == TIMER_TYPE_WALLTIME_THREAD) {
759 pState->timer_thread_subscription_id = pyi_timing_thread_subscribe(pState->interval);
760 if (pState->timer_thread_subscription_id < 0) {
761 PyErr_Format(PyExc_RuntimeError, "failed to subscribe to timing thread: error %d", pState->timer_thread_subscription_id);
762 goto error;
763 }
764 } else if (timer_type_int == TIMER_TYPE_WALLTIME_COARSE) {
765 pState->floatclock_type = PYI_FLOATCLOCK_MONOTONIC_COARSE;
766 } else {
767 pState->floatclock_type = PYI_FLOATCLOCK_DEFAULT;
768 }
769
770 // initialise the last invocation to avoid immediate callback
771 pState->last_invocation = ProfilerState_GetTime(pState);
772
773 if (context_var) {
774 Py_INCREF(context_var);
775 pState->context_var = context_var;
776
777 if (!ProfilerState_UpdateContextVar(pState)) {
778 goto error;
779 }
780 }
781
782 PyEval_SetProfile(profile, (PyObject *)pState);
783 Py_DECREF(pState); // We've given a reference to SetProfile, so we release ours.
784 } else {
785 PyEval_SetProfile(NULL, NULL);
786 }
787
788 Py_RETURN_NONE;
789
790 error:
791 Py_XDECREF(pState);
792 return NULL;
793 }
794
795
796 static PyObject *
797 get_frame_info(PyObject *m, PyObject *const *args, Py_ssize_t nargs)
798 {
799 if (nargs != 1) {
800 PyErr_SetString(PyExc_TypeError, "get_frame_info takes exactly 1 argument");
801 return NULL;
802 }
803
804 if (!PyFrame_Check(args[0])) {
805 PyErr_SetString(PyExc_TypeError, "get_frame_info should be called with a Frame object");
806 return NULL;
807 }
808
809 PyFrameObject *frame = (PyFrameObject *)args[0];
810
811 return _get_frame_info(frame);
812 }
813
814 static inline double
815 measure_timing_overhead_for_timer(PYIFloatClockType timer) {
816 int n = 1000;
817 int num_iterations = 0;
818 pyi_floatclock(timer); // warmup
819 double start = pyi_floatclock(timer);
820 double end = start;
821 double duration = 0;
822 for (int i = 0; i < n; i++) {
823 end = pyi_floatclock(timer);
824 duration = end - start;
825 num_iterations += 1;
826 if (duration > 0.0001) {
827 // dont run this for more than 100us
828 break;
829 }
830 }
831 return duration / num_iterations;
832 }
833
834 static PyObject *
835 measure_timing_overhead(PyObject *m, PyObject * Py_UNUSED(args))
836 {
837 double monotonic_coarse_resolution = pyi_monotonic_coarse_resolution();
838 int is_course_timer_available = monotonic_coarse_resolution != DBL_MAX;
839
840 PyObject *result = PyDict_New();
841 PyObject *value = PyFloat_FromDouble(measure_timing_overhead_for_timer(PYI_FLOATCLOCK_DEFAULT));
842 PyDict_SetItemString(result, "walltime", value);
843 Py_DECREF(value);
844 if (is_course_timer_available) {
845 value = PyFloat_FromDouble(measure_timing_overhead_for_timer(PYI_FLOATCLOCK_MONOTONIC_COARSE));
846 PyDict_SetItemString(result, "walltime_coarse", value);
847 Py_DECREF(value);
848 }
849
850 return result;
851 }
852
853 static PyObject *
854 walltime_coarse_resolution(PyObject *m, PyObject * Py_UNUSED(args))
855 {
856 double resolution = pyi_monotonic_coarse_resolution();
857 if (resolution == DBL_MAX) {
858 Py_RETURN_NONE;
859 }
860 return PyFloat_FromDouble(resolution);
861 }
862
863 ///////////////////////////
864 // Module initialization //
865 ///////////////////////////
866
867 static PyMethodDef module_methods[] = {
868 {"setstatprofile", (PyCFunction)setstatprofile, METH_VARARGS | METH_KEYWORDS,
869 "Sets the statistical profiler callback. The function in the same manner as setprofile, but "
870 "instead of being called every on every call and return, the function is called every "
871 "<interval> seconds with the current stack."},
872 {"get_frame_info", (PyCFunction)get_frame_info, METH_FASTCALL,
873 "Returns the frame identifier string for the given Frame object."},
874 {"measure_timing_overhead", (PyCFunction)measure_timing_overhead, METH_NOARGS,
875 "Returns a dict showing how much overhead the timing options have."},
876 {"walltime_coarse_resolution", (PyCFunction)walltime_coarse_resolution, METH_NOARGS,
877 "Returns the resolution of the monotonic coarse clock. Returns None if the clock is not available."},
878 {NULL} /* Sentinel */
879 };
880
881 PyMODINIT_FUNC PyInit_stat_profile(void)
882 {
883 PyType_Ready(&ProfilerState_Type);
884
885 static struct PyModuleDef moduledef = {
886 PyModuleDef_HEAD_INIT,
887 "stat_profile",
888 "Module that implements the backend to a statistical profiler",
889 -1,
890 module_methods
891 };
892
893 if (stat_profile_init() == -1)
894 return NULL;
895
896 return PyModule_Create(&moduledef);
897 }