Created
November 6, 2021 00:40
-
-
Save VinayakBagaria/96e129fd2db0424292f2a9b7fcee0ace to your computer and use it in GitHub Desktop.
Decorator to add profiling to Python code using CProfile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cProfile | |
import io | |
import pstats | |
is_profiler_enabled = False | |
def profile(func): | |
def enabled_wrapper(*args, **kwargs): | |
pr = cProfile.Profile() | |
pr.enable() | |
retval = func(*args, **kwargs) | |
pr.disable() | |
s = io.StringIO() | |
sortby = pstats.SortKey.CUMULATIVE # 'cumulative' | |
ps = pstats.Stats(pr, stream=s).sort_stats(sortby) | |
ps.print_stats() | |
print(s.getvalue()) | |
return retval | |
def disabled_wrapper(*args, **kwargs): | |
retval = func(*args, **kwargs) | |
return retval | |
return enabled_wrapper if is_profiler_enabled else disabled_wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment