Coverage for pyxfem/core/exec_tools.py: 67%
18 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-10-24 07:17 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-10-24 07:17 +0000
1"""
2Code profiling utilities.
4This module provides a singleton-style wrapper around Python's built-in
5:mod:`cProfile` and :mod:`pstats` modules to toggle and inspect profiling
6data across code sections.
7Created on Fri Dec 29 16:58:47 2023
9@author: nchevaug
10"""
12import cProfile
13import pstats
16class Profile:
17 """
18 Static controller for runtime performance profiling.
20 Wraps a global :class:`cProfile.Profile` instance, allowing selective
21 activation, deactivation, and reporting of cumulative execution statistics.
23 Attributes
24 ----------
25 doprofile : bool
26 Global toggle flag. When set to ``False``, all profiling calls
27 are bypassed (default is ``True``).
28 pr : cProfile.Profile
29 Underlying profiler instance.
30 """
31 doprofile = True
32 pr = cProfile.Profile()
34 @classmethod
35 def enable(cls):
36 """Start collecting profiling data if :attr:`doprofile` is enabled."""
37 if Profile.doprofile:
38 Profile.pr.enable()
40 @classmethod
41 def disable(cls):
42 """Stop collecting profiling data if :attr:`doprofile` is enabled."""
43 if Profile.doprofile:
44 Profile.pr.disable()
46 @classmethod
47 def print_stats(cls, nlines=50):
48 """
49 Print profiling statistics sorted by cumulative runtime.
51 Parameters
52 ----------
53 nlines : int, optional
54 Maximum number of top-ranked lines/functions to display
55 (default is 50).
56 """
57 if Profile.doprofile:
58 ps = pstats.Stats(Profile.pr).sort_stats(pstats.SortKey.CUMULATIVE)
59 ps.print_stats(nlines)
60 #Profile.pr.print_stats(sort="cumulative")