task-time 4.2 KB

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