If you write a library of a reasonable size, it will be troublesome to execute a script from the command line and write setUp and tearDown of unittest every time you profile, so make a decorator.
d_profile.py
import cProfile
import pstats
def profile(func):
def _f(*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
print("\n<<<---")
res = func(*args, **kwargs)
p = pstats.Stats(pr)
p.strip_dirs().sort_stats('cumtime').print_stats(20)
print("\n--->>>")
return res
return _f
You can pinpoint profile only for specific functions and methods. Comment out the decorator if you want to disable the profile. Of course, you can also use it when you want to profile only a specific test method with unittest.
func.py
from d_profile import profile
@profile
def hoge(a, b):
return a * b
Recommended Posts