Source code for pyxfem.core.exec_tools

"""
Code profiling utilities.

This module provides a singleton-style wrapper around Python's built-in
:mod:`cProfile` and :mod:`pstats` modules to toggle and inspect profiling
data across code sections.
Created on Fri Dec 29 16:58:47 2023

@author: nchevaug
"""

import cProfile
import pstats


[docs] class Profile: """ Static controller for runtime performance profiling. Wraps a global :class:`cProfile.Profile` instance, allowing selective activation, deactivation, and reporting of cumulative execution statistics. Attributes ---------- doprofile : bool Global toggle flag. When set to ``False``, all profiling calls are bypassed (default is ``True``). pr : cProfile.Profile Underlying profiler instance. """ doprofile = True pr = cProfile.Profile()
[docs] @classmethod def enable(cls): """Start collecting profiling data if :attr:`doprofile` is enabled.""" if Profile.doprofile: Profile.pr.enable()
[docs] @classmethod def disable(cls): """Stop collecting profiling data if :attr:`doprofile` is enabled.""" if Profile.doprofile: Profile.pr.disable()
[docs] @classmethod def print_stats(cls, nlines=50): """ Print profiling statistics sorted by cumulative runtime. Parameters ---------- nlines : int, optional Maximum number of top-ranked lines/functions to display (default is 50). """ if Profile.doprofile: ps = pstats.Stats(Profile.pr).sort_stats(pstats.SortKey.CUMULATIVE) ps.print_stats(nlines)
#Profile.pr.print_stats(sort="cumulative")