| 1 |
#!/usr/bin/env python |
| 2 |
# |
| 3 |
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation) |
| 4 |
# Copyright (c) 2008-2016 California Institute of Technology. |
| 5 |
# Copyright (c) 2016-2026 The Uncertainty Quantification Foundation. |
| 6 |
# License: 3-clause BSD. The full license text is available at: |
| 7 |
# - https://github.com/uqfoundation/dill/blob/master/LICENSE |
| 8 |
''' |
| 9 |
build profile graph for the given instance |
| 10 |
|
| 11 |
running: |
| 12 |
$ get_gprof <args> <instance> |
| 13 |
|
| 14 |
executes: |
| 15 |
gprof2dot -f pstats <args> <type>.prof | dot -Tpng -o <type>.call.png |
| 16 |
|
| 17 |
where: |
| 18 |
<args> are arguments for gprof2dot, such as "-n 5 -e 5" |
| 19 |
<instance> is code to create the instance to profile |
| 20 |
<type> is the class of the instance (i.e. type(instance)) |
| 21 |
|
| 22 |
For example: |
| 23 |
$ get_gprof -n 5 -e 1 "import numpy; numpy.array([1,2])" |
| 24 |
|
| 25 |
will create 'ndarray.call.png' with the profile graph for numpy.array([1,2]), |
| 26 |
where '-n 5' eliminates nodes below 5% threshold, similarly '-e 1' eliminates |
| 27 |
edges below 1% threshold |
| 28 |
''' |
| 29 |
|
| 30 |
if __name__ == "__main__": |
| 31 |
import sys |
| 32 |
if len(sys.argv) < 2: |
| 33 |
print ("Please provide an object instance (e.g. 'import math; math.pi')") |
| 34 |
sys.exit() |
| 35 |
# grab args for gprof2dot |
| 36 |
args = sys.argv[1:-1] |
| 37 |
args = ' '.join(args) |
| 38 |
# last arg builds the object |
| 39 |
obj = sys.argv[-1] |
| 40 |
obj = obj.split(';') |
| 41 |
# multi-line prep for generating an instance |
| 42 |
for line in obj[:-1]: |
| 43 |
exec(line) |
| 44 |
# one-line generation of an instance |
| 45 |
try: |
| 46 |
obj = eval(obj[-1]) |
| 47 |
except Exception: |
| 48 |
print ("Error processing object instance") |
| 49 |
sys.exit() |
| 50 |
|
| 51 |
# get object 'name' |
| 52 |
objtype = type(obj) |
| 53 |
name = getattr(objtype, '__name__', getattr(objtype, '__class__', objtype)) |
| 54 |
|
| 55 |
# profile dumping an object |
| 56 |
import dill |
| 57 |
import os |
| 58 |
import cProfile |
| 59 |
#name = os.path.splitext(os.path.basename(__file__))[0] |
| 60 |
cProfile.run("dill.dumps(obj)", filename="%s.prof" % name) |
| 61 |
msg = "gprof2dot -f pstats %s %s.prof | dot -Tpng -o %s.call.png" % (args, name, name) |
| 62 |
try: |
| 63 |
res = os.system(msg) |
| 64 |
except Exception: |
| 65 |
print ("Please verify install of 'gprof2dot' to view profile graphs") |
| 66 |
if res: |
| 67 |
print ("Please verify install of 'gprof2dot' to view profile graphs") |
| 68 |
|
| 69 |
# get stats |
| 70 |
f_prof = "%s.prof" % name |
| 71 |
import pstats |
| 72 |
stats = pstats.Stats(f_prof, stream=sys.stdout) |
| 73 |
stats.strip_dirs().sort_stats('cumtime') |
| 74 |
stats.print_stats(20) #XXX: save to file instead of print top 20? |
| 75 |
os.remove(f_prof) |