Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Add ability to run statprof as a module #16

Open
wants to merge 3 commits into from

2 participants

@nvie

This supports the following usage pattern, similar to other profiling tools, or pdb:

$ python -m statprof myscript.py
<output of myscript here>
 time    seconds   seconds  name
 93.67      0.20      0.20  myscript.py:8:main
  2.53      0.01      0.01  myscript.py:7:main
  1.90      0.00      0.00  myscript.py:9:main
  1.27      0.00      0.00  myscript.py:6:main
  0.63      0.00      0.00  myscript.py:10:main
  0.00      0.21      0.00  runpy.py:162:_run_module_as_main
  0.00      0.21      0.00  myscript.py:18:<module>
  0.00      0.21      0.00  statprof.py:471:<module>
  0.00      0.21      0.00  runpy.py:72:_run_code
  0.00      0.21      0.00  statprof.py:468:main
---
Sample count: 158
Total time: 0.210000 seconds
@zyv

Can be closed if #17 is merged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
Showing with 36 additions and 1 deletion.
  1. +36 −1 statprof.py
View
37 statprof.py
@@ -104,6 +104,7 @@
import os
import signal
+import sys
from collections import defaultdict
from contextlib import contextmanager
@@ -329,7 +330,6 @@ def display(fp=None, format=0):
'''Print statistics, either to stdout or the given file object.'''
if fp is None:
- import sys
fp = sys.stdout
if state.sample_count == 0:
print >> fp, ('No samples recorded.')
@@ -429,3 +429,38 @@ def display_by_method(fp):
call.self_secs_in_proc,
call.lineno,
source))
+
+def _runscript(filename):
+ import __main__
+ __main__.__dict__.clear()
+ __main__.__dict__.update({
+ "__name__": "__main__",
+ "__file__": filename,
+ "__builtins__": __builtins__,
+ })
+ execfile(filename)
+
+def main():
+ '''Run the given script under the profiler, when invoked as a module
+ (python -m statprof ...), and display the profile report once done.
+ '''
+ if not sys.argv[1:] or sys.argv[1] in ('--help', '-h'):
+ print 'usage: python -m statprof <script> [<args>]'
+ sys.exit(2)
+
+ scriptfile = sys.argv[1]
+ if not os.path.exists(scriptfile):
+ print 'Error:', scriptfile, 'does not exist'
+ sys.exit(1)
+
+ del sys.argv[0] # Hide 'statprof' from argument list
+
+ # Replace statprof's dir with script's dir in front of module search path
+ sys.path[0] = os.path.dirname(os.path.realpath(scriptfile))
+
+ with profile():
+ _runscript(scriptfile)
+
+if __name__ == '__main__':
+ import statprof
+ statprof.main()
Something went wrong with that request. Please try again.