task-time 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. #!/usr/bin/env python3
  2. import argparse
  3. import os
  4. import re
  5. import sys
  6. arg_parser = argparse.ArgumentParser(
  7. description="""
  8. Reports time consumed for one or more task in a format similar to the standard
  9. Bash 'time' builtin. Optionally sorts tasks by real (wall-clock), user (user
  10. space CPU), or sys (kernel CPU) time.
  11. """)
  12. arg_parser.add_argument(
  13. "paths",
  14. metavar="path",
  15. nargs="+",
  16. help="""
  17. A path containing task buildstats. If the path is a directory, e.g.
  18. build/tmp/buildstats, then all task found (recursively) in it will be
  19. processed. If the path is a single task buildstat, e.g.
  20. build/tmp/buildstats/20161018083535/foo-1.0-r0/do_compile, then just that
  21. buildstat will be processed. Multiple paths can be specified to process all of
  22. them. Files whose names do not start with "do_" are ignored.
  23. """)
  24. arg_parser.add_argument(
  25. "--sort",
  26. choices=("none", "real", "user", "sys"),
  27. default="none",
  28. help="""
  29. The measurement to sort the output by. Defaults to 'none', which means to sort
  30. by the order paths were given on the command line. For other options, tasks are
  31. sorted in descending order from the highest value.
  32. """)
  33. args = arg_parser.parse_args()
  34. # Field names and regexes for parsing out their values from buildstat files
  35. field_regexes = (("elapsed", ".*Elapsed time: ([0-9.]+)"),
  36. ("user", "rusage ru_utime: ([0-9.]+)"),
  37. ("sys", "rusage ru_stime: ([0-9.]+)"),
  38. ("child user", "Child rusage ru_utime: ([0-9.]+)"),
  39. ("child sys", "Child rusage ru_stime: ([0-9.]+)"))
  40. # A list of (<path>, <dict>) tuples, where <path> is the path of a do_* task
  41. # buildstat file and <dict> maps fields from the file to their values
  42. task_infos = []
  43. def save_times_for_task(path):
  44. """Saves information for the buildstat file 'path' in 'task_infos'."""
  45. if not os.path.basename(path).startswith("do_"):
  46. return
  47. with open(path) as f:
  48. fields = {}
  49. for line in f:
  50. for name, regex in field_regexes:
  51. match = re.match(regex, line)
  52. if match:
  53. fields[name] = float(match.group(1))
  54. break
  55. # Check that all expected fields were present
  56. for name, regex in field_regexes:
  57. if name not in fields:
  58. print("Warning: Skipping '{}' because no field matching '{}' could be found"
  59. .format(path, regex),
  60. file=sys.stderr)
  61. return
  62. task_infos.append((path, fields))
  63. def save_times_for_dir(path):
  64. """Runs save_times_for_task() for each file in path and its subdirs, recursively."""
  65. # Raise an exception for os.walk() errors instead of ignoring them
  66. def walk_onerror(e):
  67. raise e
  68. for root, _, files in os.walk(path, onerror=walk_onerror):
  69. for fname in files:
  70. save_times_for_task(os.path.join(root, fname))
  71. for path in args.paths:
  72. if os.path.isfile(path):
  73. save_times_for_task(path)
  74. else:
  75. save_times_for_dir(path)
  76. def elapsed_time(task_info):
  77. return task_info[1]["elapsed"]
  78. def tot_user_time(task_info):
  79. return task_info[1]["user"] + task_info[1]["child user"]
  80. def tot_sys_time(task_info):
  81. return task_info[1]["sys"] + task_info[1]["child sys"]
  82. if args.sort != "none":
  83. sort_fn = {"real": elapsed_time, "user": tot_user_time, "sys": tot_sys_time}
  84. task_infos.sort(key=sort_fn[args.sort], reverse=True)
  85. first_entry = True
  86. # Catching BrokenPipeError avoids annoying errors when the output is piped into
  87. # e.g. 'less' or 'head' and not completely read
  88. try:
  89. for task_info in task_infos:
  90. real = elapsed_time(task_info)
  91. user = tot_user_time(task_info)
  92. sys = tot_sys_time(task_info)
  93. if not first_entry:
  94. print()
  95. first_entry = False
  96. # Mimic Bash's 'time' builtin
  97. print("{}:\n"
  98. "real\t{}m{:.3f}s\n"
  99. "user\t{}m{:.3f}s\n"
  100. "sys\t{}m{:.3f}s"
  101. .format(task_info[0],
  102. int(real//60), real%60,
  103. int(user//60), user%60,
  104. int(sys//60), sys%60))
  105. except BrokenPipeError:
  106. pass