PageRenderTime 50ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/tool/memusage/memusage.py

https://bitbucket.org/quangquach/pypy
Python | 63 lines | 56 code | 0 blank | 7 comment | 0 complexity | a2adc5c894d23f6c85bcb5d5aaa5382d MD5 | raw file
  1. #! /usr/bin/env python
  2. """
  3. Usage: memusage.py [-o filename] command [args...]
  4. Runs a subprocess, and measure its RSS (resident set size) every second.
  5. At the end, print the maximum RSS measured, and some statistics.
  6. Also writes "filename", reporting every second the RSS. If filename is not
  7. given, the output is written to "memusage.log"
  8. """
  9. import sys, os, re, time
  10. def parse_args():
  11. args = sys.argv[1:]
  12. if args[0] == '-o':
  13. args.pop(0)
  14. outname = args.pop(0)
  15. else:
  16. outname = 'memusage.log'
  17. args[0] # make sure there is at least one argument left
  18. return outname, args
  19. try:
  20. outname, args = parse_args()
  21. except IndexError:
  22. print >> sys.stderr, __doc__.strip()
  23. sys.exit(2)
  24. childpid = os.fork()
  25. if childpid == 0:
  26. os.execvp(args[0], args)
  27. sys.exit(1)
  28. r = re.compile("VmRSS:\s*(\d+)")
  29. filename = '/proc/%d/status' % childpid
  30. rss_max = 0
  31. rss_sum = 0
  32. rss_count = 0
  33. f = open(outname, 'w', 0)
  34. while os.waitpid(childpid, os.WNOHANG)[0] == 0:
  35. g = open(filename)
  36. s = g.read()
  37. g.close()
  38. match = r.search(s)
  39. if not match: # VmRSS is missing if the process just finished
  40. break
  41. rss = int(match.group(1))
  42. print >> f, rss
  43. if rss > rss_max: rss_max = rss
  44. rss_sum += rss
  45. rss_count += 1
  46. time.sleep(1)
  47. f.close()
  48. if rss_count > 0:
  49. print
  50. print 'Memory usage:'
  51. print '\tmaximum RSS: %10d kb' % rss_max
  52. print '\tmean RSS: %10d kb' % (rss_sum / rss_count)
  53. print '\trun time: %10d s' % rss_count