Skip to content

Instantly share code, notes, and snippets.

@timmow
Created March 2, 2015 16:06
Show Gist options
  • Select an option

  • Save timmow/15e0d69acca67bebc627 to your computer and use it in GitHub Desktop.

Select an option

Save timmow/15e0d69acca67bebc627 to your computer and use it in GitHub Desktop.
Profiling Python
GDS Profiling Python
pip install grpof2dot
pip install graphviz
gprof2dot -f pstats /tmp/-1422538070.52.profile | dot -Tpng -o output.png
How to create a .profile file in /tmp:
Add the following de
import cProfile
import time
def do_profile(prefix='', keys=[]):
def do_profile_wrapper(func):
def profiled_func(*args, **kwargs):
profile = cProfile.Profile()
if len(keys) > 0:
suffix = '-' + \
'-'.join([kwargs.get(k, 'no_val') for k in keys])
else:
suffix = ''
filename = '/tmp/{}{}-{}.profile'.format(
prefix,
suffix,
str(time.time())
)
try:
profile.enable()
result = func(*args, **kwargs)
profile.disable()
return result
finally:
profile.dump_stats(filename)
return profiled_func
return do_profile_wrapper
Then wrap the method to be profiled with
@method_decorator(do_profile())
Note - @method_decorator required in wrapping a method in a class
e.g.
@method_decorator(permission_required('signin'))
@method_decorator(never_cache)
@method_decorator(vary_on_headers('Authorization'))
@method_decorator(do_profile())
def get(self, user, request, **kwargs):
kwargs['user'] = user
return super(DataSetView, self).get(
request,
**kwargs)
Eager loading might solve the problem:
https://docs.djangoproject.com/en/1.7/ref/models/querysets/#select-related
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment