get_gprof 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!C:\Users\liuyu\Desktop\LoFTR\python\py\python.exe
  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. running:
  11. $ get_gprof <args> <instance>
  12. executes:
  13. gprof2dot -f pstats <args> <type>.prof | dot -Tpng -o <type>.call.png
  14. where:
  15. <args> are arguments for gprof2dot, such as "-n 5 -e 5"
  16. <instance> is code to create the instance to profile
  17. <type> is the class of the instance (i.e. type(instance))
  18. For example:
  19. $ get_gprof -n 5 -e 1 "import numpy; numpy.array([1,2])"
  20. will create 'ndarray.call.png' with the profile graph for numpy.array([1,2]),
  21. where '-n 5' eliminates nodes below 5% threshold, similarly '-e 1' eliminates
  22. edges below 1% threshold
  23. '''
  24. if __name__ == "__main__":
  25. import sys
  26. if len(sys.argv) < 2:
  27. print ("Please provide an object instance (e.g. 'import math; math.pi')")
  28. sys.exit()
  29. # grab args for gprof2dot
  30. args = sys.argv[1:-1]
  31. args = ' '.join(args)
  32. # last arg builds the object
  33. obj = sys.argv[-1]
  34. obj = obj.split(';')
  35. # multi-line prep for generating an instance
  36. for line in obj[:-1]:
  37. exec(line)
  38. # one-line generation of an instance
  39. try:
  40. obj = eval(obj[-1])
  41. except Exception:
  42. print ("Error processing object instance")
  43. sys.exit()
  44. # get object 'name'
  45. objtype = type(obj)
  46. name = getattr(objtype, '__name__', getattr(objtype, '__class__', objtype))
  47. # profile dumping an object
  48. import dill
  49. import os
  50. import cProfile
  51. #name = os.path.splitext(os.path.basename(__file__))[0]
  52. cProfile.run("dill.dumps(obj)", filename="%s.prof" % name)
  53. msg = "gprof2dot -f pstats %s %s.prof | dot -Tpng -o %s.call.png" % (args, name, name)
  54. try:
  55. res = os.system(msg)
  56. except Exception:
  57. print ("Please verify install of 'gprof2dot' to view profile graphs")
  58. if res:
  59. print ("Please verify install of 'gprof2dot' to view profile graphs")
  60. # get stats
  61. f_prof = "%s.prof" % name
  62. import pstats
  63. stats = pstats.Stats(f_prof, stream=sys.stdout)
  64. stats.strip_dirs().sort_stats('cumtime')
  65. stats.print_stats(20) #XXX: save to file instead of print top 20?
  66. os.remove(f_prof)