Skip to content

Commit

Permalink
Allow statprof to be run as a standalone executable, to profile a sep…
Browse files Browse the repository at this point in the history
…arate call
  • Loading branch information
cpennington committed Mar 15, 2017
1 parent 3242031 commit a451719
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ Or with a contextmanager : ::
with statprof.profile():
my_questionable_function()

Or as a separate executable: ::

statprof my_questionable_script

The profiler can be invoked at more than one place inside your code and will
report its findings for all of them at once at the end: ::

Expand Down
3 changes: 3 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,8 @@ def read(fname):
"Operating System :: Unix",
"Topic :: Utilities",
],
entry_points={
'console_scripts': ['statprof=statprof:main']
},
**extra
)
44 changes: 44 additions & 0 deletions statprof.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@
import signal
import sys

from argparse import ArgumentParser
from collections import defaultdict, namedtuple
from contextlib import contextmanager

Expand Down Expand Up @@ -484,3 +485,46 @@ def display_by_csv(fp, sort_order):
row.cum_time_in_proc,
row.cum_secs_in_proc,
))


def main(args=sys.argv):
parser = ArgumentParser()
parser.add_argument('progname', type=str)

formats = {
'line': DisplayFormats.ByLine,
'method': DisplayFormats.ByMethod,
'csv': DisplayFormats.CSV,
}
parser.add_argument('--format', type=str, choices=formats, default='line')
parser.add_argument('--outfile', type=str, default=None)

sorts = {
'cum': SortOrders.ByCumulative,
'self': SortOrders.BySelf,
}
parser.add_argument('--sort', type=str, choices=sorts, default='self')
parser.add_argument('--quiet', action='store_true')
opts, rest = parser.parse_known_args(args[1:])

sys.path.insert(0, os.path.dirname(opts.progname))
with open(opts.progname, 'rb') as fp:
code = compile(fp.read(), opts.progname, 'exec')
globs = {
'__file__': opts.progname,
'__name__': '__main__',
'__package__': None,
}

if opts.outfile is None:
outfile = sys.stdout
else:
outfile = open(opts.outfile('w'))

with profile(not opts.quiet, outfile, formats[opts.format], sorts[opts.sort]):
sys.argv = [opts.progname] + rest
exec code in globs, None


if __name__ == "__main__":
sys.exit(main(sys.argv))

0 comments on commit a451719

Please sign in to comment.