Skip to content

Instantly share code, notes, and snippets.

@VinayakBagaria
Created November 6, 2021 00:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VinayakBagaria/96e129fd2db0424292f2a9b7fcee0ace to your computer and use it in GitHub Desktop.
Save VinayakBagaria/96e129fd2db0424292f2a9b7fcee0ace to your computer and use it in GitHub Desktop.
Decorator to add profiling to Python code using CProfile
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