Last active
November 10, 2016 07:15
-
-
Save whitekid/306780790c93f1776265597c7023b077 to your computer and use it in GitHub Desktop.
Profile show
This file contains hidden or 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
#!/usr/bin/env python | |
# -*- coding: utf8 -*- | |
"""very very simple profile viewer | |
To generate profile data run: | |
python -m cProfile -o profile.dump myscript | |
OR | |
from cProfile import Profile | |
pr = Profile() | |
pr.enable() | |
... foo ... | |
pr.disable() | |
pr.dump_stats('profile.dump') | |
OR | |
pr = Profile() | |
pr.runcall(method, args...) | |
pr.dump_stats('profile.dump') | |
OR | |
@profile('profile.dump') | |
def foo(*args, **kwargs): | |
print args, kwargs | |
""" | |
import functools | |
import pstats | |
import sys | |
import click | |
def profile(dump=None): | |
def wrap(func): | |
@functools.wraps(func) | |
def wrapper(*args, **kwargs): | |
from cProfile import Profile | |
profile = Profile() | |
try: | |
return profile.runcall(func, *args, **kwargs) | |
finally: | |
if not dump: | |
profile.print_stats() | |
else: | |
profile.dump_stats(dump) | |
return wrapper | |
return wrap | |
@click.command() | |
@click.option('-s', 'sort', default='tottime', | |
help='sort by') | |
@click.option('-o', 'option', default='', | |
help="print options. eg) /opt,0.1") | |
@click.option('-r', 'reversed', flag_value=True, help='reverse') | |
@click.option('-c', 'caller', default='', help="print caller") | |
@click.argument('file', nargs=1) | |
def main(sort, option, reversed, caller, file): | |
"""Python profile viewer | |
see https://docs.python.org/3/library/profile.html#pstats.Stats.sort_stats | |
""" | |
def try_float(f): | |
try: | |
return float(f) | |
except ValueError: | |
return f | |
sort = [_ for _ in sort.split(',') if _] | |
caller = [_ for _ in caller.split(',') if _] | |
option = [try_float(_) for _ in option.split(',') if _] | |
ps = pstats.Stats(file) | |
ps.sort_stats(*sort) | |
if reversed: | |
ps.reverse_order() | |
if caller: | |
ps.print_callers(*caller) | |
else: | |
ps.print_stats(*option) | |
if __name__ == '__main__': | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment