post_build_ninja_summary.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. # Copyright (c) 2018 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Summarize the last ninja build, invoked with ninja's -C syntax.
  5. This script is designed to be automatically run after each ninja build in
  6. order to summarize the build's performance. Making build performance information
  7. more visible should make it easier to notice anomalies and opportunities. To use
  8. this script on Windows just set NINJA_SUMMARIZE_BUILD=1 and run autoninja.bat.
  9. On Linux you can get autoninja to invoke this script using this syntax:
  10. $ NINJA_SUMMARIZE_BUILD=1 autoninja -C out/Default/ chrome
  11. You can also call this script directly using ninja's syntax to specify the
  12. output directory of interest:
  13. > python post_build_ninja_summary.py -C out/Default
  14. Typical output looks like this:
  15. >ninja -C out\debug_component base
  16. ninja.exe -C out\debug_component base -j 960 -l 48 -d keeprsp
  17. ninja: Entering directory `out\debug_component'
  18. [1 processes, 1/1 @ 0.3/s : 3.092s ] Regenerating ninja files
  19. Longest build steps:
  20. 0.1 weighted s to build obj/base/base/trace_log.obj (6.7 s elapsed time)
  21. 0.2 weighted s to build nasm.exe, nasm.exe.pdb (0.2 s elapsed time)
  22. 0.3 weighted s to build obj/base/base/win_util.obj (12.4 s elapsed time)
  23. 1.2 weighted s to build base.dll, base.dll.lib (1.2 s elapsed time)
  24. Time by build-step type:
  25. 0.0 s weighted time to generate 6 .lib files (0.3 s elapsed time sum)
  26. 0.1 s weighted time to generate 25 .stamp files (1.2 s elapsed time sum)
  27. 0.2 s weighted time to generate 20 .o files (2.8 s elapsed time sum)
  28. 1.7 s weighted time to generate 4 PEFile (linking) files (2.0 s elapsed
  29. time sum)
  30. 23.9 s weighted time to generate 770 .obj files (974.8 s elapsed time sum)
  31. 26.1 s weighted time (982.9 s elapsed time sum, 37.7x parallelism)
  32. 839 build steps completed, average of 32.17/s
  33. If no gn clean has been done then results will be for the last non-NULL
  34. invocation of ninja. Ideas for future statistics, and implementations are
  35. appreciated.
  36. The "weighted" time is the elapsed time of each build step divided by the number
  37. of tasks that were running in parallel. This makes it an excellent approximation
  38. of how "important" a slow step was. A link that is entirely or mostly serialized
  39. will have a weighted time that is the same or similar to its elapsed time. A
  40. compile that runs in parallel with 999 other compiles will have a weighted time
  41. that is tiny."""
  42. from __future__ import print_function
  43. import argparse
  44. import errno
  45. import os
  46. import sys
  47. # The number of long build times to report:
  48. long_count = 10
  49. # The number of long times by extension to report
  50. long_ext_count = 5
  51. class Target:
  52. """Represents a single line read for a .ninja_log file."""
  53. def __init__(self, start, end):
  54. """Creates a target object by passing in the start/end times in seconds
  55. as a float."""
  56. self.start = start
  57. self.end = end
  58. # A list of targets, appended to by the owner of this object.
  59. self.targets = []
  60. self.weighted_duration = 0.0
  61. def Duration(self):
  62. """Returns the task duration in seconds as a float."""
  63. return self.end - self.start
  64. def SetWeightedDuration(self, weighted_duration):
  65. """Sets the duration, in seconds, passed in as a float."""
  66. self.weighted_duration = weighted_duration
  67. def WeightedDuration(self):
  68. """Returns the task's weighted duration in seconds as a float.
  69. Weighted_duration takes the elapsed time of the task and divides it
  70. by how many other tasks were running at the same time. Thus, it
  71. represents the approximate impact of this task on the total build time,
  72. with serialized or serializing steps typically ending up with much
  73. longer weighted durations.
  74. weighted_duration should always be the same or shorter than duration.
  75. """
  76. # Allow for modest floating-point errors
  77. epsilon = 0.000002
  78. if (self.weighted_duration > self.Duration() + epsilon):
  79. print('%s > %s?' % (self.weighted_duration, self.Duration()))
  80. assert(self.weighted_duration <= self.Duration() + epsilon)
  81. return self.weighted_duration
  82. def DescribeTargets(self):
  83. """Returns a printable string that summarizes the targets."""
  84. if len(self.targets) == 1:
  85. return self.targets[0]
  86. # Some build steps generate dozens of outputs - handle them sanely.
  87. # It's a bit odd that if there are three targets we return all three
  88. # but if there are more than three we just return two, but this works
  89. # well in practice.
  90. elif len(self.targets) > 3:
  91. return '(%d items) ' % len(self.targets) + (
  92. ', '.join(self.targets[:2]) + ', ...')
  93. else:
  94. return ', '.join(self.targets)
  95. # Copied with some modifications from ninjatracing
  96. def ReadTargets(log, show_all):
  97. """Reads all targets from .ninja_log file |log_file|, sorted by duration.
  98. The result is a list of Target objects."""
  99. header = log.readline()
  100. assert header == '# ninja log v5\n', \
  101. 'unrecognized ninja log version %r' % header
  102. targets_dict = {}
  103. last_end_seen = 0.0
  104. for line in log:
  105. parts = line.strip().split('\t')
  106. if len(parts) != 5:
  107. # If ninja.exe is rudely halted then the .ninja_log file may be
  108. # corrupt. Silently continue.
  109. continue
  110. start, end, _, name, cmdhash = parts # Ignore restat.
  111. # Convert from integral milliseconds to float seconds.
  112. start = int(start) / 1000.0
  113. end = int(end) / 1000.0
  114. if not show_all and end < last_end_seen:
  115. # An earlier time stamp means that this step is the first in a new
  116. # build, possibly an incremental build. Throw away the previous
  117. # data so that this new build will be displayed independently.
  118. # This has to be done by comparing end times because records are
  119. # written to the .ninja_log file when commands complete, so end
  120. # times are guaranteed to be in order, but start times are not.
  121. targets_dict = {}
  122. target = None
  123. if cmdhash in targets_dict:
  124. target = targets_dict[cmdhash]
  125. if not show_all and (target.start != start or target.end != end):
  126. # If several builds in a row just run one or two build steps then
  127. # the end times may not go backwards so the last build may not be
  128. # detected as such. However in many cases there will be a build step
  129. # repeated in the two builds and the changed start/stop points for
  130. # that command, identified by the hash, can be used to detect and
  131. # reset the target dictionary.
  132. targets_dict = {}
  133. target = None
  134. if not target:
  135. targets_dict[cmdhash] = target = Target(start, end)
  136. last_end_seen = end
  137. target.targets.append(name)
  138. return targets_dict.values()
  139. def GetExtension(target):
  140. """Return the file extension that best represents a target.
  141. For targets that generate multiple outputs it is important to return a
  142. consistent 'canonical' extension. Ultimately the goal is to group build steps
  143. by type."""
  144. for output in target.targets:
  145. # Normalize all mojo related outputs to 'mojo'.
  146. if output.count('.mojom') > 0:
  147. extension = 'mojo'
  148. break
  149. # Not a true extension, but a good grouping.
  150. if output.endswith('type_mappings'):
  151. extension = 'type_mappings'
  152. break
  153. extension = os.path.splitext(output)[1]
  154. if len(extension) == 0:
  155. extension = '(no extension found)'
  156. if extension in ['.pdb', '.dll', '.exe']:
  157. extension = 'PEFile (linking)'
  158. # Make sure that .dll and .exe are grouped together and that the
  159. # .dll.lib files don't cause these to be listed as libraries
  160. break
  161. if extension in ['.so', '.TOC']:
  162. extension = '.so (linking)'
  163. # Attempt to identify linking, avoid identifying as '.TOC'
  164. break
  165. return extension
  166. def SummarizeEntries(entries):
  167. """Print a summary of the passed in list of Target objects."""
  168. # Create a list that is in order by time stamp and has entries for the
  169. # beginning and ending of each build step (one time stamp may have multiple
  170. # entries due to multiple steps starting/stopping at exactly the same time).
  171. # Iterate through this list, keeping track of which tasks are running at all
  172. # times. At each time step calculate a running total for weighted time so
  173. # that when each task ends its own weighted time can easily be calculated.
  174. task_start_stop_times = []
  175. earliest = -1
  176. latest = 0
  177. total_cpu_time = 0
  178. for target in entries:
  179. if earliest < 0 or target.start < earliest:
  180. earliest = target.start
  181. if target.end > latest:
  182. latest = target.end
  183. total_cpu_time += target.Duration()
  184. task_start_stop_times.append((target.start, 'start', target))
  185. task_start_stop_times.append((target.end, 'stop', target))
  186. length = latest - earliest
  187. weighted_total = 0.0
  188. task_start_stop_times.sort()
  189. # Now we have all task start/stop times sorted by when they happen. If a
  190. # task starts and stops on the same time stamp then the start will come
  191. # first because of the alphabet, which is important for making this work
  192. # correctly.
  193. # Track the tasks which are currently running.
  194. running_tasks = {}
  195. # Record the time we have processed up to so we know how to calculate time
  196. # deltas.
  197. last_time = task_start_stop_times[0][0]
  198. # Track the accumulated weighted time so that it can efficiently be added
  199. # to individual tasks.
  200. last_weighted_time = 0.0
  201. # Scan all start/stop events.
  202. for event in task_start_stop_times:
  203. time, action_name, target = event
  204. # Accumulate weighted time up to now.
  205. num_running = len(running_tasks)
  206. if num_running > 0:
  207. # Update the total weighted time up to this moment.
  208. last_weighted_time += (time - last_time) / float(num_running)
  209. if action_name == 'start':
  210. # Record the total weighted task time when this task starts.
  211. running_tasks[target] = last_weighted_time
  212. if action_name == 'stop':
  213. # Record the change in the total weighted task time while this task ran.
  214. weighted_duration = last_weighted_time - running_tasks[target]
  215. target.SetWeightedDuration(weighted_duration)
  216. weighted_total += weighted_duration
  217. del running_tasks[target]
  218. last_time = time
  219. assert(len(running_tasks) == 0)
  220. # Warn if the sum of weighted times is off by more than half a second.
  221. if abs(length - weighted_total) > 500:
  222. print('Discrepancy!!! Length = %.3f, weighted total = %.3f' % (
  223. length, weighted_total))
  224. # Print the slowest build steps (by weighted time).
  225. print(' Longest build steps:')
  226. entries.sort(key=lambda x: x.WeightedDuration())
  227. for target in entries[-long_count:]:
  228. print(' %8.1f weighted s to build %s (%.1f s elapsed time)' % (
  229. target.WeightedDuration(),
  230. target.DescribeTargets(), target.Duration()))
  231. # Sum up the time by file extension/type of the output file
  232. count_by_ext = {}
  233. time_by_ext = {}
  234. weighted_time_by_ext = {}
  235. # Scan through all of the targets to build up per-extension statistics.
  236. for target in entries:
  237. extension = GetExtension(target)
  238. time_by_ext[extension] = time_by_ext.get(extension, 0) + target.Duration()
  239. weighted_time_by_ext[extension] = weighted_time_by_ext.get(extension,
  240. 0) + target.WeightedDuration()
  241. count_by_ext[extension] = count_by_ext.get(extension, 0) + 1
  242. print(' Time by build-step type:')
  243. # Copy to a list with extension name and total time swapped, to (time, ext)
  244. weighted_time_by_ext_sorted = sorted((y, x) for (x, y) in
  245. weighted_time_by_ext.items())
  246. # Print the slowest build target types (by weighted time):
  247. for time, extension in weighted_time_by_ext_sorted[-long_ext_count:]:
  248. print(' %8.1f s weighted time to generate %d %s files '
  249. '(%1.1f s elapsed time sum)' % (time, count_by_ext[extension],
  250. extension, time_by_ext[extension]))
  251. print(' %.1f s weighted time (%.1f s elapsed time sum, %1.1fx '
  252. 'parallelism)' % (length, total_cpu_time,
  253. total_cpu_time * 1.0 / length))
  254. print(' %d build steps completed, average of %1.2f/s' % (
  255. len(entries), len(entries) / (length)))
  256. def main():
  257. log_file = '.ninja_log'
  258. parser = argparse.ArgumentParser()
  259. parser.add_argument('-C', dest='build_directory',
  260. help='Build directory.')
  261. parser.add_argument('--log-file',
  262. help="specific ninja log file to analyze.")
  263. args, _extra_args = parser.parse_known_args()
  264. if args.build_directory:
  265. log_file = os.path.join(args.build_directory, log_file)
  266. if args.log_file:
  267. log_file = args.log_file
  268. try:
  269. with open(log_file, 'r') as log:
  270. entries = ReadTargets(log, False)
  271. SummarizeEntries(entries)
  272. except IOError:
  273. print('Log file %r not found, no build summary created.' % log_file)
  274. return errno.ENOENT
  275. if __name__ == '__main__':
  276. sys.exit(main())