Skip to content

Instantly share code, notes, and snippets.

@durden
Created December 4, 2013 15:52
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 durden/7789930 to your computer and use it in GitHub Desktop.
Save durden/7789930 to your computer and use it in GitHub Desktop.
Awesome decorator using line_profiler with ability to specify which sub-functions to follow.
# Taken from: https://zapier.com/engineering/profiling-python-boss/
try:
from line_profiler import LineProfiler
def do_profile(follow=[]):
def inner(func):
def profiled_func(*args, **kwargs):
try:
profiler = LineProfiler()
profiler.add_function(func)
for f in follow:
profiler.add_function(f)
profiler.enable_by_count()
return func(*args, **kwargs)
finally:
profiler.print_stats()
return profiled_func
return inner
except ImportError:
def do_profile(follow=[]):
"Helpful if you accidentally leave in production!"
def inner(func):
def nothing(*args, **kwargs):
return func(*args, **kwargs)
return nothing
return inner
def get_number():
for x in xrange(5000000):
yield x
@do_profile(follow=[get_number])
def expensive_function():
for x in get_number():
i = x ^ x ^ x
return 'some result!'
result = expensive_function()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment