You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1502 lines
48 KiB

6 years ago
  1. #!/usr/bin/env python
  2. #
  3. # scons-time - run SCons timings and collect statistics
  4. #
  5. # A script for running a configuration through SCons with a standard
  6. # set of invocations to collect timing and memory statistics and to
  7. # capture the results in a consistent set of output files for display
  8. # and analysis.
  9. #
  10. #
  11. # Copyright (c) 2001 - 2017 The SCons Foundation
  12. #
  13. # Permission is hereby granted, free of charge, to any person obtaining
  14. # a copy of this software and associated documentation files (the
  15. # "Software"), to deal in the Software without restriction, including
  16. # without limitation the rights to use, copy, modify, merge, publish,
  17. # distribute, sublicense, and/or sell copies of the Software, and to
  18. # permit persons to whom the Software is furnished to do so, subject to
  19. # the following conditions:
  20. #
  21. # The above copyright notice and this permission notice shall be included
  22. # in all copies or substantial portions of the Software.
  23. #
  24. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  25. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  26. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. from __future__ import division, print_function
  32. __revision__ = "src/script/scons-time.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  33. import getopt
  34. import glob
  35. import os
  36. import re
  37. import shutil
  38. import sys
  39. import tempfile
  40. import time
  41. def make_temp_file(**kw):
  42. try:
  43. result = tempfile.mktemp(**kw)
  44. result = os.path.realpath(result)
  45. except TypeError:
  46. try:
  47. save_template = tempfile.template
  48. prefix = kw['prefix']
  49. del kw['prefix']
  50. tempfile.template = prefix
  51. result = tempfile.mktemp(**kw)
  52. finally:
  53. tempfile.template = save_template
  54. return result
  55. def HACK_for_exec(cmd, *args):
  56. '''
  57. For some reason, Python won't allow an exec() within a function
  58. that also declares an internal function (including lambda functions).
  59. This function is a hack that calls exec() in a function with no
  60. internal functions.
  61. '''
  62. if not args: exec(cmd)
  63. elif len(args) == 1: exec(cmd, args[0])
  64. else: exec(cmd, args[0], args[1])
  65. class Plotter(object):
  66. def increment_size(self, largest):
  67. """
  68. Return the size of each horizontal increment line for a specified
  69. maximum value. This returns a value that will provide somewhere
  70. between 5 and 9 horizontal lines on the graph, on some set of
  71. boundaries that are multiples of 10/100/1000/etc.
  72. """
  73. i = largest // 5
  74. if not i:
  75. return largest
  76. multiplier = 1
  77. while i >= 10:
  78. i = i // 10
  79. multiplier = multiplier * 10
  80. return i * multiplier
  81. def max_graph_value(self, largest):
  82. # Round up to next integer.
  83. largest = int(largest) + 1
  84. increment = self.increment_size(largest)
  85. return ((largest + increment - 1) // increment) * increment
  86. class Line(object):
  87. def __init__(self, points, type, title, label, comment, fmt="%s %s"):
  88. self.points = points
  89. self.type = type
  90. self.title = title
  91. self.label = label
  92. self.comment = comment
  93. self.fmt = fmt
  94. def print_label(self, inx, x, y):
  95. if self.label:
  96. print('set label %s "%s" at %0.1f,%0.1f right' % (inx, self.label, x, y))
  97. def plot_string(self):
  98. if self.title:
  99. title_string = 'title "%s"' % self.title
  100. else:
  101. title_string = 'notitle'
  102. return "'-' %s with lines lt %s" % (title_string, self.type)
  103. def print_points(self, fmt=None):
  104. if fmt is None:
  105. fmt = self.fmt
  106. if self.comment:
  107. print('# %s' % self.comment)
  108. for x, y in self.points:
  109. # If y is None, it usually represents some kind of break
  110. # in the line's index number. We might want to represent
  111. # this some way rather than just drawing the line straight
  112. # between the two points on either side.
  113. if not y is None:
  114. print(fmt % (x, y))
  115. print('e')
  116. def get_x_values(self):
  117. return [ p[0] for p in self.points ]
  118. def get_y_values(self):
  119. return [ p[1] for p in self.points ]
  120. class Gnuplotter(Plotter):
  121. def __init__(self, title, key_location):
  122. self.lines = []
  123. self.title = title
  124. self.key_location = key_location
  125. def line(self, points, type, title=None, label=None, comment=None, fmt='%s %s'):
  126. if points:
  127. line = Line(points, type, title, label, comment, fmt)
  128. self.lines.append(line)
  129. def plot_string(self, line):
  130. return line.plot_string()
  131. def vertical_bar(self, x, type, label, comment):
  132. if self.get_min_x() <= x and x <= self.get_max_x():
  133. points = [(x, 0), (x, self.max_graph_value(self.get_max_y()))]
  134. self.line(points, type, label, comment)
  135. def get_all_x_values(self):
  136. result = []
  137. for line in self.lines:
  138. result.extend(line.get_x_values())
  139. return [r for r in result if not r is None]
  140. def get_all_y_values(self):
  141. result = []
  142. for line in self.lines:
  143. result.extend(line.get_y_values())
  144. return [r for r in result if not r is None]
  145. def get_min_x(self):
  146. try:
  147. return self.min_x
  148. except AttributeError:
  149. try:
  150. self.min_x = min(self.get_all_x_values())
  151. except ValueError:
  152. self.min_x = 0
  153. return self.min_x
  154. def get_max_x(self):
  155. try:
  156. return self.max_x
  157. except AttributeError:
  158. try:
  159. self.max_x = max(self.get_all_x_values())
  160. except ValueError:
  161. self.max_x = 0
  162. return self.max_x
  163. def get_min_y(self):
  164. try:
  165. return self.min_y
  166. except AttributeError:
  167. try:
  168. self.min_y = min(self.get_all_y_values())
  169. except ValueError:
  170. self.min_y = 0
  171. return self.min_y
  172. def get_max_y(self):
  173. try:
  174. return self.max_y
  175. except AttributeError:
  176. try:
  177. self.max_y = max(self.get_all_y_values())
  178. except ValueError:
  179. self.max_y = 0
  180. return self.max_y
  181. def draw(self):
  182. if not self.lines:
  183. return
  184. if self.title:
  185. print('set title "%s"' % self.title)
  186. print('set key %s' % self.key_location)
  187. min_y = self.get_min_y()
  188. max_y = self.max_graph_value(self.get_max_y())
  189. incr = (max_y - min_y) / 10.0
  190. start = min_y + (max_y / 2.0) + (2.0 * incr)
  191. position = [ start - (i * incr) for i in range(5) ]
  192. inx = 1
  193. for line in self.lines:
  194. line.print_label(inx, line.points[0][0]-1,
  195. position[(inx-1) % len(position)])
  196. inx += 1
  197. plot_strings = [ self.plot_string(l) for l in self.lines ]
  198. print('plot ' + ', \\\n '.join(plot_strings))
  199. for line in self.lines:
  200. line.print_points()
  201. def untar(fname):
  202. import tarfile
  203. tar = tarfile.open(name=fname, mode='r')
  204. for tarinfo in tar:
  205. tar.extract(tarinfo)
  206. tar.close()
  207. def unzip(fname):
  208. import zipfile
  209. zf = zipfile.ZipFile(fname, 'r')
  210. for name in zf.namelist():
  211. dir = os.path.dirname(name)
  212. try:
  213. os.makedirs(dir)
  214. except:
  215. pass
  216. open(name, 'wb').write(zf.read(name))
  217. def read_tree(dir):
  218. for dirpath, dirnames, filenames in os.walk(dir):
  219. for fn in filenames:
  220. fn = os.path.join(dirpath, fn)
  221. if os.path.isfile(fn):
  222. open(fn, 'rb').read()
  223. def redirect_to_file(command, log):
  224. return '%s > %s 2>&1' % (command, log)
  225. def tee_to_file(command, log):
  226. return '%s 2>&1 | tee %s' % (command, log)
  227. class SConsTimer(object):
  228. """
  229. Usage: scons-time SUBCOMMAND [ARGUMENTS]
  230. Type "scons-time help SUBCOMMAND" for help on a specific subcommand.
  231. Available subcommands:
  232. func Extract test-run data for a function
  233. help Provides help
  234. mem Extract --debug=memory data from test runs
  235. obj Extract --debug=count data from test runs
  236. time Extract --debug=time data from test runs
  237. run Runs a test configuration
  238. """
  239. name = 'scons-time'
  240. name_spaces = ' '*len(name)
  241. def makedict(**kw):
  242. return kw
  243. default_settings = makedict(
  244. aegis = 'aegis',
  245. aegis_project = None,
  246. chdir = None,
  247. config_file = None,
  248. initial_commands = [],
  249. key_location = 'bottom left',
  250. orig_cwd = os.getcwd(),
  251. outdir = None,
  252. prefix = '',
  253. python = '"%s"' % sys.executable,
  254. redirect = redirect_to_file,
  255. scons = None,
  256. scons_flags = '--debug=count --debug=memory --debug=time --debug=memoizer',
  257. scons_lib_dir = None,
  258. scons_wrapper = None,
  259. startup_targets = '--help',
  260. subdir = None,
  261. subversion_url = None,
  262. svn = 'svn',
  263. svn_co_flag = '-q',
  264. tar = 'tar',
  265. targets = '',
  266. targets0 = None,
  267. targets1 = None,
  268. targets2 = None,
  269. title = None,
  270. unzip = 'unzip',
  271. verbose = False,
  272. vertical_bars = [],
  273. unpack_map = {
  274. '.tar.gz' : (untar, '%(tar)s xzf %%s'),
  275. '.tgz' : (untar, '%(tar)s xzf %%s'),
  276. '.tar' : (untar, '%(tar)s xf %%s'),
  277. '.zip' : (unzip, '%(unzip)s %%s'),
  278. },
  279. )
  280. run_titles = [
  281. 'Startup',
  282. 'Full build',
  283. 'Up-to-date build',
  284. ]
  285. run_commands = [
  286. '%(python)s %(scons_wrapper)s %(scons_flags)s --profile=%(prof0)s %(targets0)s',
  287. '%(python)s %(scons_wrapper)s %(scons_flags)s --profile=%(prof1)s %(targets1)s',
  288. '%(python)s %(scons_wrapper)s %(scons_flags)s --profile=%(prof2)s %(targets2)s',
  289. ]
  290. stages = [
  291. 'pre-read',
  292. 'post-read',
  293. 'pre-build',
  294. 'post-build',
  295. ]
  296. stage_strings = {
  297. 'pre-read' : 'Memory before reading SConscript files:',
  298. 'post-read' : 'Memory after reading SConscript files:',
  299. 'pre-build' : 'Memory before building targets:',
  300. 'post-build' : 'Memory after building targets:',
  301. }
  302. memory_string_all = 'Memory '
  303. default_stage = stages[-1]
  304. time_strings = {
  305. 'total' : 'Total build time',
  306. 'SConscripts' : 'Total SConscript file execution time',
  307. 'SCons' : 'Total SCons execution time',
  308. 'commands' : 'Total command execution time',
  309. }
  310. time_string_all = 'Total .* time'
  311. #
  312. def __init__(self):
  313. self.__dict__.update(self.default_settings)
  314. # Functions for displaying and executing commands.
  315. def subst(self, x, dictionary):
  316. try:
  317. return x % dictionary
  318. except TypeError:
  319. # x isn't a string (it's probably a Python function),
  320. # so just return it.
  321. return x
  322. def subst_variables(self, command, dictionary):
  323. """
  324. Substitutes (via the format operator) the values in the specified
  325. dictionary into the specified command.
  326. The command can be an (action, string) tuple. In all cases, we
  327. perform substitution on strings and don't worry if something isn't
  328. a string. (It's probably a Python function to be executed.)
  329. """
  330. try:
  331. command + ''
  332. except TypeError:
  333. action = command[0]
  334. string = command[1]
  335. args = command[2:]
  336. else:
  337. action = command
  338. string = action
  339. args = (())
  340. action = self.subst(action, dictionary)
  341. string = self.subst(string, dictionary)
  342. return (action, string, args)
  343. def _do_not_display(self, msg, *args):
  344. pass
  345. def display(self, msg, *args):
  346. """
  347. Displays the specified message.
  348. Each message is prepended with a standard prefix of our name
  349. plus the time.
  350. """
  351. if callable(msg):
  352. msg = msg(*args)
  353. else:
  354. msg = msg % args
  355. if msg is None:
  356. return
  357. fmt = '%s[%s]: %s\n'
  358. sys.stdout.write(fmt % (self.name, time.strftime('%H:%M:%S'), msg))
  359. def _do_not_execute(self, action, *args):
  360. pass
  361. def execute(self, action, *args):
  362. """
  363. Executes the specified action.
  364. The action is called if it's a callable Python function, and
  365. otherwise passed to os.system().
  366. """
  367. if callable(action):
  368. action(*args)
  369. else:
  370. os.system(action % args)
  371. def run_command_list(self, commands, dict):
  372. """
  373. Executes a list of commands, substituting values from the
  374. specified dictionary.
  375. """
  376. commands = [ self.subst_variables(c, dict) for c in commands ]
  377. for action, string, args in commands:
  378. self.display(string, *args)
  379. sys.stdout.flush()
  380. status = self.execute(action, *args)
  381. if status:
  382. sys.exit(status)
  383. def log_display(self, command, log):
  384. command = self.subst(command, self.__dict__)
  385. if log:
  386. command = self.redirect(command, log)
  387. return command
  388. def log_execute(self, command, log):
  389. command = self.subst(command, self.__dict__)
  390. output = os.popen(command).read()
  391. if self.verbose:
  392. sys.stdout.write(output)
  393. # TODO: Figure out
  394. # Not sure we need to write binary here
  395. open(log, 'w').write(output)
  396. #
  397. def archive_splitext(self, path):
  398. """
  399. Splits an archive name into a filename base and extension.
  400. This is like os.path.splitext() (which it calls) except that it
  401. also looks for '.tar.gz' and treats it as an atomic extensions.
  402. """
  403. if path.endswith('.tar.gz'):
  404. return path[:-7], path[-7:]
  405. else:
  406. return os.path.splitext(path)
  407. def args_to_files(self, args, tail=None):
  408. """
  409. Takes a list of arguments, expands any glob patterns, and
  410. returns the last "tail" files from the list.
  411. """
  412. files = []
  413. for a in args:
  414. files.extend(sorted(glob.glob(a)))
  415. if tail:
  416. files = files[-tail:]
  417. return files
  418. def ascii_table(self, files, columns,
  419. line_function, file_function=lambda x: x,
  420. *args, **kw):
  421. header_fmt = ' '.join(['%12s'] * len(columns))
  422. line_fmt = header_fmt + ' %s'
  423. print(header_fmt % columns)
  424. for file in files:
  425. t = line_function(file, *args, **kw)
  426. if t is None:
  427. t = []
  428. diff = len(columns) - len(t)
  429. if diff > 0:
  430. t += [''] * diff
  431. t.append(file_function(file))
  432. print(line_fmt % tuple(t))
  433. def collect_results(self, files, function, *args, **kw):
  434. results = {}
  435. for file in files:
  436. base = os.path.splitext(file)[0]
  437. run, index = base.split('-')[-2:]
  438. run = int(run)
  439. index = int(index)
  440. value = function(file, *args, **kw)
  441. try:
  442. r = results[index]
  443. except KeyError:
  444. r = []
  445. results[index] = r
  446. r.append((run, value))
  447. return results
  448. def doc_to_help(self, obj):
  449. """
  450. Translates an object's __doc__ string into help text.
  451. This strips a consistent number of spaces from each line in the
  452. help text, essentially "outdenting" the text to the left-most
  453. column.
  454. """
  455. doc = obj.__doc__
  456. if doc is None:
  457. return ''
  458. return self.outdent(doc)
  459. def find_next_run_number(self, dir, prefix):
  460. """
  461. Returns the next run number in a directory for the specified prefix.
  462. Examines the contents the specified directory for files with the
  463. specified prefix, extracts the run numbers from each file name,
  464. and returns the next run number after the largest it finds.
  465. """
  466. x = re.compile(re.escape(prefix) + '-([0-9]+).*')
  467. matches = [x.match(e) for e in os.listdir(dir)]
  468. matches = [_f for _f in matches if _f]
  469. if not matches:
  470. return 0
  471. run_numbers = [int(m.group(1)) for m in matches]
  472. return int(max(run_numbers)) + 1
  473. def gnuplot_results(self, results, fmt='%s %.3f'):
  474. """
  475. Prints out a set of results in Gnuplot format.
  476. """
  477. gp = Gnuplotter(self.title, self.key_location)
  478. for i in sorted(results.keys()):
  479. try:
  480. t = self.run_titles[i]
  481. except IndexError:
  482. t = '??? %s ???' % i
  483. results[i].sort()
  484. gp.line(results[i], i+1, t, None, t, fmt=fmt)
  485. for bar_tuple in self.vertical_bars:
  486. try:
  487. x, type, label, comment = bar_tuple
  488. except ValueError:
  489. x, type, label = bar_tuple
  490. comment = label
  491. gp.vertical_bar(x, type, label, comment)
  492. gp.draw()
  493. def logfile_name(self, invocation):
  494. """
  495. Returns the absolute path of a log file for the specificed
  496. invocation number.
  497. """
  498. name = self.prefix_run + '-%d.log' % invocation
  499. return os.path.join(self.outdir, name)
  500. def outdent(self, s):
  501. """
  502. Strip as many spaces from each line as are found at the beginning
  503. of the first line in the list.
  504. """
  505. lines = s.split('\n')
  506. if lines[0] == '':
  507. lines = lines[1:]
  508. spaces = re.match(' *', lines[0]).group(0)
  509. def strip_initial_spaces(l, s=spaces):
  510. if l.startswith(spaces):
  511. l = l[len(spaces):]
  512. return l
  513. return '\n'.join([ strip_initial_spaces(l) for l in lines ]) + '\n'
  514. def profile_name(self, invocation):
  515. """
  516. Returns the absolute path of a profile file for the specified
  517. invocation number.
  518. """
  519. name = self.prefix_run + '-%d.prof' % invocation
  520. return os.path.join(self.outdir, name)
  521. def set_env(self, key, value):
  522. os.environ[key] = value
  523. #
  524. def get_debug_times(self, file, time_string=None):
  525. """
  526. Fetch times from the --debug=time strings in the specified file.
  527. """
  528. if time_string is None:
  529. search_string = self.time_string_all
  530. else:
  531. search_string = time_string
  532. contents = open(file).read()
  533. if not contents:
  534. sys.stderr.write('file %s has no contents!\n' % repr(file))
  535. return None
  536. result = re.findall(r'%s: ([\d\.]*)' % search_string, contents)[-4:]
  537. result = [ float(r) for r in result ]
  538. if not time_string is None:
  539. try:
  540. result = result[0]
  541. except IndexError:
  542. sys.stderr.write('file %s has no results!\n' % repr(file))
  543. return None
  544. return result
  545. def get_function_profile(self, file, function):
  546. """
  547. Returns the file, line number, function name, and cumulative time.
  548. """
  549. try:
  550. import pstats
  551. except ImportError as e:
  552. sys.stderr.write('%s: func: %s\n' % (self.name, e))
  553. sys.stderr.write('%s This version of Python is missing the profiler.\n' % self.name_spaces)
  554. sys.stderr.write('%s Cannot use the "func" subcommand.\n' % self.name_spaces)
  555. sys.exit(1)
  556. statistics = pstats.Stats(file).stats
  557. matches = [ e for e in statistics.items() if e[0][2] == function ]
  558. r = matches[0]
  559. return r[0][0], r[0][1], r[0][2], r[1][3]
  560. def get_function_time(self, file, function):
  561. """
  562. Returns just the cumulative time for the specified function.
  563. """
  564. return self.get_function_profile(file, function)[3]
  565. def get_memory(self, file, memory_string=None):
  566. """
  567. Returns a list of integers of the amount of memory used. The
  568. default behavior is to return all the stages.
  569. """
  570. if memory_string is None:
  571. search_string = self.memory_string_all
  572. else:
  573. search_string = memory_string
  574. lines = open(file).readlines()
  575. lines = [ l for l in lines if l.startswith(search_string) ][-4:]
  576. result = [ int(l.split()[-1]) for l in lines[-4:] ]
  577. if len(result) == 1:
  578. result = result[0]
  579. return result
  580. def get_object_counts(self, file, object_name, index=None):
  581. """
  582. Returns the counts of the specified object_name.
  583. """
  584. object_string = ' ' + object_name + '\n'
  585. lines = open(file).readlines()
  586. line = [ l for l in lines if l.endswith(object_string) ][0]
  587. result = [ int(field) for field in line.split()[:4] ]
  588. if index is not None:
  589. result = result[index]
  590. return result
  591. #
  592. command_alias = {}
  593. def execute_subcommand(self, argv):
  594. """
  595. Executes the do_*() function for the specified subcommand (argv[0]).
  596. """
  597. if not argv:
  598. return
  599. cmdName = self.command_alias.get(argv[0], argv[0])
  600. try:
  601. func = getattr(self, 'do_' + cmdName)
  602. except AttributeError:
  603. return self.default(argv)
  604. try:
  605. return func(argv)
  606. except TypeError as e:
  607. sys.stderr.write("%s %s: %s\n" % (self.name, cmdName, e))
  608. import traceback
  609. traceback.print_exc(file=sys.stderr)
  610. sys.stderr.write("Try '%s help %s'\n" % (self.name, cmdName))
  611. def default(self, argv):
  612. """
  613. The default behavior for an unknown subcommand. Prints an
  614. error message and exits.
  615. """
  616. sys.stderr.write('%s: Unknown subcommand "%s".\n' % (self.name, argv[0]))
  617. sys.stderr.write('Type "%s help" for usage.\n' % self.name)
  618. sys.exit(1)
  619. #
  620. def do_help(self, argv):
  621. """
  622. """
  623. if argv[1:]:
  624. for arg in argv[1:]:
  625. try:
  626. func = getattr(self, 'do_' + arg)
  627. except AttributeError:
  628. sys.stderr.write('%s: No help for "%s"\n' % (self.name, arg))
  629. else:
  630. try:
  631. help = getattr(self, 'help_' + arg)
  632. except AttributeError:
  633. sys.stdout.write(self.doc_to_help(func))
  634. sys.stdout.flush()
  635. else:
  636. help()
  637. else:
  638. doc = self.doc_to_help(self.__class__)
  639. if doc:
  640. sys.stdout.write(doc)
  641. sys.stdout.flush()
  642. return None
  643. #
  644. def help_func(self):
  645. help = """\
  646. Usage: scons-time func [OPTIONS] FILE [...]
  647. -C DIR, --chdir=DIR Change to DIR before looking for files
  648. -f FILE, --file=FILE Read configuration from specified FILE
  649. --fmt=FORMAT, --format=FORMAT Print data in specified FORMAT
  650. --func=NAME, --function=NAME Report time for function NAME
  651. -h, --help Print this help and exit
  652. -p STRING, --prefix=STRING Use STRING as log file/profile prefix
  653. -t NUMBER, --tail=NUMBER Only report the last NUMBER files
  654. --title=TITLE Specify the output plot TITLE
  655. """
  656. sys.stdout.write(self.outdent(help))
  657. sys.stdout.flush()
  658. def do_func(self, argv):
  659. """
  660. """
  661. format = 'ascii'
  662. function_name = '_main'
  663. tail = None
  664. short_opts = '?C:f:hp:t:'
  665. long_opts = [
  666. 'chdir=',
  667. 'file=',
  668. 'fmt=',
  669. 'format=',
  670. 'func=',
  671. 'function=',
  672. 'help',
  673. 'prefix=',
  674. 'tail=',
  675. 'title=',
  676. ]
  677. opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
  678. for o, a in opts:
  679. if o in ('-C', '--chdir'):
  680. self.chdir = a
  681. elif o in ('-f', '--file'):
  682. self.config_file = a
  683. elif o in ('--fmt', '--format'):
  684. format = a
  685. elif o in ('--func', '--function'):
  686. function_name = a
  687. elif o in ('-?', '-h', '--help'):
  688. self.do_help(['help', 'func'])
  689. sys.exit(0)
  690. elif o in ('--max',):
  691. max_time = int(a)
  692. elif o in ('-p', '--prefix'):
  693. self.prefix = a
  694. elif o in ('-t', '--tail'):
  695. tail = int(a)
  696. elif o in ('--title',):
  697. self.title = a
  698. if self.config_file:
  699. exec(open(self.config_file, 'r').read(), self.__dict__)
  700. if self.chdir:
  701. os.chdir(self.chdir)
  702. if not args:
  703. pattern = '%s*.prof' % self.prefix
  704. args = self.args_to_files([pattern], tail)
  705. if not args:
  706. if self.chdir:
  707. directory = self.chdir
  708. else:
  709. directory = os.getcwd()
  710. sys.stderr.write('%s: func: No arguments specified.\n' % self.name)
  711. sys.stderr.write('%s No %s*.prof files found in "%s".\n' % (self.name_spaces, self.prefix, directory))
  712. sys.stderr.write('%s Type "%s help func" for help.\n' % (self.name_spaces, self.name))
  713. sys.exit(1)
  714. else:
  715. args = self.args_to_files(args, tail)
  716. cwd_ = os.getcwd() + os.sep
  717. if format == 'ascii':
  718. for file in args:
  719. try:
  720. f, line, func, time = \
  721. self.get_function_profile(file, function_name)
  722. except ValueError as e:
  723. sys.stderr.write("%s: func: %s: %s\n" %
  724. (self.name, file, e))
  725. else:
  726. if f.startswith(cwd_):
  727. f = f[len(cwd_):]
  728. print("%.3f %s:%d(%s)" % (time, f, line, func))
  729. elif format == 'gnuplot':
  730. results = self.collect_results(args, self.get_function_time,
  731. function_name)
  732. self.gnuplot_results(results)
  733. else:
  734. sys.stderr.write('%s: func: Unknown format "%s".\n' % (self.name, format))
  735. sys.exit(1)
  736. #
  737. def help_mem(self):
  738. help = """\
  739. Usage: scons-time mem [OPTIONS] FILE [...]
  740. -C DIR, --chdir=DIR Change to DIR before looking for files
  741. -f FILE, --file=FILE Read configuration from specified FILE
  742. --fmt=FORMAT, --format=FORMAT Print data in specified FORMAT
  743. -h, --help Print this help and exit
  744. -p STRING, --prefix=STRING Use STRING as log file/profile prefix
  745. --stage=STAGE Plot memory at the specified stage:
  746. pre-read, post-read, pre-build,
  747. post-build (default: post-build)
  748. -t NUMBER, --tail=NUMBER Only report the last NUMBER files
  749. --title=TITLE Specify the output plot TITLE
  750. """
  751. sys.stdout.write(self.outdent(help))
  752. sys.stdout.flush()
  753. def do_mem(self, argv):
  754. format = 'ascii'
  755. logfile_path = lambda x: x
  756. stage = self.default_stage
  757. tail = None
  758. short_opts = '?C:f:hp:t:'
  759. long_opts = [
  760. 'chdir=',
  761. 'file=',
  762. 'fmt=',
  763. 'format=',
  764. 'help',
  765. 'prefix=',
  766. 'stage=',
  767. 'tail=',
  768. 'title=',
  769. ]
  770. opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
  771. for o, a in opts:
  772. if o in ('-C', '--chdir'):
  773. self.chdir = a
  774. elif o in ('-f', '--file'):
  775. self.config_file = a
  776. elif o in ('--fmt', '--format'):
  777. format = a
  778. elif o in ('-?', '-h', '--help'):
  779. self.do_help(['help', 'mem'])
  780. sys.exit(0)
  781. elif o in ('-p', '--prefix'):
  782. self.prefix = a
  783. elif o in ('--stage',):
  784. if not a in self.stages:
  785. sys.stderr.write('%s: mem: Unrecognized stage "%s".\n' % (self.name, a))
  786. sys.exit(1)
  787. stage = a
  788. elif o in ('-t', '--tail'):
  789. tail = int(a)
  790. elif o in ('--title',):
  791. self.title = a
  792. if self.config_file:
  793. HACK_for_exec(open(self.config_file, 'r').read(), self.__dict__)
  794. if self.chdir:
  795. os.chdir(self.chdir)
  796. logfile_path = lambda x: os.path.join(self.chdir, x)
  797. if not args:
  798. pattern = '%s*.log' % self.prefix
  799. args = self.args_to_files([pattern], tail)
  800. if not args:
  801. if self.chdir:
  802. directory = self.chdir
  803. else:
  804. directory = os.getcwd()
  805. sys.stderr.write('%s: mem: No arguments specified.\n' % self.name)
  806. sys.stderr.write('%s No %s*.log files found in "%s".\n' % (self.name_spaces, self.prefix, directory))
  807. sys.stderr.write('%s Type "%s help mem" for help.\n' % (self.name_spaces, self.name))
  808. sys.exit(1)
  809. else:
  810. args = self.args_to_files(args, tail)
  811. cwd_ = os.getcwd() + os.sep
  812. if format == 'ascii':
  813. self.ascii_table(args, tuple(self.stages), self.get_memory, logfile_path)
  814. elif format == 'gnuplot':
  815. results = self.collect_results(args, self.get_memory,
  816. self.stage_strings[stage])
  817. self.gnuplot_results(results)
  818. else:
  819. sys.stderr.write('%s: mem: Unknown format "%s".\n' % (self.name, format))
  820. sys.exit(1)
  821. return 0
  822. #
  823. def help_obj(self):
  824. help = """\
  825. Usage: scons-time obj [OPTIONS] OBJECT FILE [...]
  826. -C DIR, --chdir=DIR Change to DIR before looking for files
  827. -f FILE, --file=FILE Read configuration from specified FILE
  828. --fmt=FORMAT, --format=FORMAT Print data in specified FORMAT
  829. -h, --help Print this help and exit
  830. -p STRING, --prefix=STRING Use STRING as log file/profile prefix
  831. --stage=STAGE Plot memory at the specified stage:
  832. pre-read, post-read, pre-build,
  833. post-build (default: post-build)
  834. -t NUMBER, --tail=NUMBER Only report the last NUMBER files
  835. --title=TITLE Specify the output plot TITLE
  836. """
  837. sys.stdout.write(self.outdent(help))
  838. sys.stdout.flush()
  839. def do_obj(self, argv):
  840. format = 'ascii'
  841. logfile_path = lambda x: x
  842. stage = self.default_stage
  843. tail = None
  844. short_opts = '?C:f:hp:t:'
  845. long_opts = [
  846. 'chdir=',
  847. 'file=',
  848. 'fmt=',
  849. 'format=',
  850. 'help',
  851. 'prefix=',
  852. 'stage=',
  853. 'tail=',
  854. 'title=',
  855. ]
  856. opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
  857. for o, a in opts:
  858. if o in ('-C', '--chdir'):
  859. self.chdir = a
  860. elif o in ('-f', '--file'):
  861. self.config_file = a
  862. elif o in ('--fmt', '--format'):
  863. format = a
  864. elif o in ('-?', '-h', '--help'):
  865. self.do_help(['help', 'obj'])
  866. sys.exit(0)
  867. elif o in ('-p', '--prefix'):
  868. self.prefix = a
  869. elif o in ('--stage',):
  870. if not a in self.stages:
  871. sys.stderr.write('%s: obj: Unrecognized stage "%s".\n' % (self.name, a))
  872. sys.stderr.write('%s Type "%s help obj" for help.\n' % (self.name_spaces, self.name))
  873. sys.exit(1)
  874. stage = a
  875. elif o in ('-t', '--tail'):
  876. tail = int(a)
  877. elif o in ('--title',):
  878. self.title = a
  879. if not args:
  880. sys.stderr.write('%s: obj: Must specify an object name.\n' % self.name)
  881. sys.stderr.write('%s Type "%s help obj" for help.\n' % (self.name_spaces, self.name))
  882. sys.exit(1)
  883. object_name = args.pop(0)
  884. if self.config_file:
  885. HACK_for_exec(open(self.config_file, 'r').read(), self.__dict__)
  886. if self.chdir:
  887. os.chdir(self.chdir)
  888. logfile_path = lambda x: os.path.join(self.chdir, x)
  889. if not args:
  890. pattern = '%s*.log' % self.prefix
  891. args = self.args_to_files([pattern], tail)
  892. if not args:
  893. if self.chdir:
  894. directory = self.chdir
  895. else:
  896. directory = os.getcwd()
  897. sys.stderr.write('%s: obj: No arguments specified.\n' % self.name)
  898. sys.stderr.write('%s No %s*.log files found in "%s".\n' % (self.name_spaces, self.prefix, directory))
  899. sys.stderr.write('%s Type "%s help obj" for help.\n' % (self.name_spaces, self.name))
  900. sys.exit(1)
  901. else:
  902. args = self.args_to_files(args, tail)
  903. cwd_ = os.getcwd() + os.sep
  904. if format == 'ascii':
  905. self.ascii_table(args, tuple(self.stages), self.get_object_counts, logfile_path, object_name)
  906. elif format == 'gnuplot':
  907. stage_index = 0
  908. for s in self.stages:
  909. if stage == s:
  910. break
  911. stage_index = stage_index + 1
  912. results = self.collect_results(args, self.get_object_counts,
  913. object_name, stage_index)
  914. self.gnuplot_results(results)
  915. else:
  916. sys.stderr.write('%s: obj: Unknown format "%s".\n' % (self.name, format))
  917. sys.exit(1)
  918. return 0
  919. #
  920. def help_run(self):
  921. help = """\
  922. Usage: scons-time run [OPTIONS] [FILE ...]
  923. --aegis=PROJECT Use SCons from the Aegis PROJECT
  924. --chdir=DIR Name of unpacked directory for chdir
  925. -f FILE, --file=FILE Read configuration from specified FILE
  926. -h, --help Print this help and exit
  927. -n, --no-exec No execute, just print command lines
  928. --number=NUMBER Put output in files for run NUMBER
  929. --outdir=OUTDIR Put output files in OUTDIR
  930. -p STRING, --prefix=STRING Use STRING as log file/profile prefix
  931. --python=PYTHON Time using the specified PYTHON
  932. -q, --quiet Don't print command lines
  933. --scons=SCONS Time using the specified SCONS
  934. --svn=URL, --subversion=URL Use SCons from Subversion URL
  935. -v, --verbose Display output of commands
  936. """
  937. sys.stdout.write(self.outdent(help))
  938. sys.stdout.flush()
  939. def do_run(self, argv):
  940. """
  941. """
  942. run_number_list = [None]
  943. short_opts = '?f:hnp:qs:v'
  944. long_opts = [
  945. 'aegis=',
  946. 'file=',
  947. 'help',
  948. 'no-exec',
  949. 'number=',
  950. 'outdir=',
  951. 'prefix=',
  952. 'python=',
  953. 'quiet',
  954. 'scons=',
  955. 'svn=',
  956. 'subdir=',
  957. 'subversion=',
  958. 'verbose',
  959. ]
  960. opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
  961. for o, a in opts:
  962. if o in ('--aegis',):
  963. self.aegis_project = a
  964. elif o in ('-f', '--file'):
  965. self.config_file = a
  966. elif o in ('-?', '-h', '--help'):
  967. self.do_help(['help', 'run'])
  968. sys.exit(0)
  969. elif o in ('-n', '--no-exec'):
  970. self.execute = self._do_not_execute
  971. elif o in ('--number',):
  972. run_number_list = self.split_run_numbers(a)
  973. elif o in ('--outdir',):
  974. self.outdir = a
  975. elif o in ('-p', '--prefix'):
  976. self.prefix = a
  977. elif o in ('--python',):
  978. self.python = a
  979. elif o in ('-q', '--quiet'):
  980. self.display = self._do_not_display
  981. elif o in ('-s', '--subdir'):
  982. self.subdir = a
  983. elif o in ('--scons',):
  984. self.scons = a
  985. elif o in ('--svn', '--subversion'):
  986. self.subversion_url = a
  987. elif o in ('-v', '--verbose'):
  988. self.redirect = tee_to_file
  989. self.verbose = True
  990. self.svn_co_flag = ''
  991. if not args and not self.config_file:
  992. sys.stderr.write('%s: run: No arguments or -f config file specified.\n' % self.name)
  993. sys.stderr.write('%s Type "%s help run" for help.\n' % (self.name_spaces, self.name))
  994. sys.exit(1)
  995. if self.config_file:
  996. exec(open(self.config_file, 'r').read(), self.__dict__)
  997. if args:
  998. self.archive_list = args
  999. archive_file_name = os.path.split(self.archive_list[0])[1]
  1000. if not self.subdir:
  1001. self.subdir = self.archive_splitext(archive_file_name)[0]
  1002. if not self.prefix:
  1003. self.prefix = self.archive_splitext(archive_file_name)[0]
  1004. prepare = None
  1005. if self.subversion_url:
  1006. prepare = self.prep_subversion_run
  1007. elif self.aegis_project:
  1008. prepare = self.prep_aegis_run
  1009. for run_number in run_number_list:
  1010. self.individual_run(run_number, self.archive_list, prepare)
  1011. def split_run_numbers(self, s):
  1012. result = []
  1013. for n in s.split(','):
  1014. try:
  1015. x, y = n.split('-')
  1016. except ValueError:
  1017. result.append(int(n))
  1018. else:
  1019. result.extend(list(range(int(x), int(y)+1)))
  1020. return result
  1021. def scons_path(self, dir):
  1022. return os.path.join(dir, 'src', 'script', 'scons.py')
  1023. def scons_lib_dir_path(self, dir):
  1024. return os.path.join(dir, 'src', 'engine')
  1025. def prep_aegis_run(self, commands, removals):
  1026. self.aegis_tmpdir = make_temp_file(prefix = self.name + '-aegis-')
  1027. removals.append((shutil.rmtree, 'rm -rf %%s', self.aegis_tmpdir))
  1028. self.aegis_parent_project = os.path.splitext(self.aegis_project)[0]
  1029. self.scons = self.scons_path(self.aegis_tmpdir)
  1030. self.scons_lib_dir = self.scons_lib_dir_path(self.aegis_tmpdir)
  1031. commands.extend([
  1032. 'mkdir %(aegis_tmpdir)s',
  1033. (lambda: os.chdir(self.aegis_tmpdir), 'cd %(aegis_tmpdir)s'),
  1034. '%(aegis)s -cp -ind -p %(aegis_parent_project)s .',
  1035. '%(aegis)s -cp -ind -p %(aegis_project)s -delta %(run_number)s .',
  1036. ])
  1037. def prep_subversion_run(self, commands, removals):
  1038. self.svn_tmpdir = make_temp_file(prefix = self.name + '-svn-')
  1039. removals.append((shutil.rmtree, 'rm -rf %%s', self.svn_tmpdir))
  1040. self.scons = self.scons_path(self.svn_tmpdir)
  1041. self.scons_lib_dir = self.scons_lib_dir_path(self.svn_tmpdir)
  1042. commands.extend([
  1043. 'mkdir %(svn_tmpdir)s',
  1044. '%(svn)s co %(svn_co_flag)s -r %(run_number)s %(subversion_url)s %(svn_tmpdir)s',
  1045. ])
  1046. def individual_run(self, run_number, archive_list, prepare=None):
  1047. """
  1048. Performs an individual run of the default SCons invocations.
  1049. """
  1050. commands = []
  1051. removals = []
  1052. if prepare:
  1053. prepare(commands, removals)
  1054. save_scons = self.scons
  1055. save_scons_wrapper = self.scons_wrapper
  1056. save_scons_lib_dir = self.scons_lib_dir
  1057. if self.outdir is None:
  1058. self.outdir = self.orig_cwd
  1059. elif not os.path.isabs(self.outdir):
  1060. self.outdir = os.path.join(self.orig_cwd, self.outdir)
  1061. if self.scons is None:
  1062. self.scons = self.scons_path(self.orig_cwd)
  1063. if self.scons_lib_dir is None:
  1064. self.scons_lib_dir = self.scons_lib_dir_path(self.orig_cwd)
  1065. if self.scons_wrapper is None:
  1066. self.scons_wrapper = self.scons
  1067. if not run_number:
  1068. run_number = self.find_next_run_number(self.outdir, self.prefix)
  1069. self.run_number = str(run_number)
  1070. self.prefix_run = self.prefix + '-%03d' % run_number
  1071. if self.targets0 is None:
  1072. self.targets0 = self.startup_targets
  1073. if self.targets1 is None:
  1074. self.targets1 = self.targets
  1075. if self.targets2 is None:
  1076. self.targets2 = self.targets
  1077. self.tmpdir = make_temp_file(prefix = self.name + '-')
  1078. commands.extend([
  1079. 'mkdir %(tmpdir)s',
  1080. (os.chdir, 'cd %%s', self.tmpdir),
  1081. ])
  1082. for archive in archive_list:
  1083. if not os.path.isabs(archive):
  1084. archive = os.path.join(self.orig_cwd, archive)
  1085. if os.path.isdir(archive):
  1086. dest = os.path.split(archive)[1]
  1087. commands.append((shutil.copytree, 'cp -r %%s %%s', archive, dest))
  1088. else:
  1089. suffix = self.archive_splitext(archive)[1]
  1090. unpack_command = self.unpack_map.get(suffix)
  1091. if not unpack_command:
  1092. dest = os.path.split(archive)[1]
  1093. commands.append((shutil.copyfile, 'cp %%s %%s', archive, dest))
  1094. else:
  1095. commands.append(unpack_command + (archive,))
  1096. commands.extend([
  1097. (os.chdir, 'cd %%s', self.subdir),
  1098. ])
  1099. commands.extend(self.initial_commands)
  1100. commands.extend([
  1101. (lambda: read_tree('.'),
  1102. 'find * -type f | xargs cat > /dev/null'),
  1103. (self.set_env, 'export %%s=%%s',
  1104. 'SCONS_LIB_DIR', self.scons_lib_dir),
  1105. '%(python)s %(scons_wrapper)s --version',
  1106. ])
  1107. index = 0
  1108. for run_command in self.run_commands:
  1109. setattr(self, 'prof%d' % index, self.profile_name(index))
  1110. c = (
  1111. self.log_execute,
  1112. self.log_display,
  1113. run_command,
  1114. self.logfile_name(index),
  1115. )
  1116. commands.append(c)
  1117. index = index + 1
  1118. commands.extend([
  1119. (os.chdir, 'cd %%s', self.orig_cwd),
  1120. ])
  1121. if not os.environ.get('PRESERVE'):
  1122. commands.extend(removals)
  1123. commands.append((shutil.rmtree, 'rm -rf %%s', self.tmpdir))
  1124. self.run_command_list(commands, self.__dict__)
  1125. self.scons = save_scons
  1126. self.scons_lib_dir = save_scons_lib_dir
  1127. self.scons_wrapper = save_scons_wrapper
  1128. #
  1129. def help_time(self):
  1130. help = """\
  1131. Usage: scons-time time [OPTIONS] FILE [...]
  1132. -C DIR, --chdir=DIR Change to DIR before looking for files
  1133. -f FILE, --file=FILE Read configuration from specified FILE
  1134. --fmt=FORMAT, --format=FORMAT Print data in specified FORMAT
  1135. -h, --help Print this help and exit
  1136. -p STRING, --prefix=STRING Use STRING as log file/profile prefix
  1137. -t NUMBER, --tail=NUMBER Only report the last NUMBER files
  1138. --which=TIMER Plot timings for TIMER: total,
  1139. SConscripts, SCons, commands.
  1140. """
  1141. sys.stdout.write(self.outdent(help))
  1142. sys.stdout.flush()
  1143. def do_time(self, argv):
  1144. format = 'ascii'
  1145. logfile_path = lambda x: x
  1146. tail = None
  1147. which = 'total'
  1148. short_opts = '?C:f:hp:t:'
  1149. long_opts = [
  1150. 'chdir=',
  1151. 'file=',
  1152. 'fmt=',
  1153. 'format=',
  1154. 'help',
  1155. 'prefix=',
  1156. 'tail=',
  1157. 'title=',
  1158. 'which=',
  1159. ]
  1160. opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
  1161. for o, a in opts:
  1162. if o in ('-C', '--chdir'):
  1163. self.chdir = a
  1164. elif o in ('-f', '--file'):
  1165. self.config_file = a
  1166. elif o in ('--fmt', '--format'):
  1167. format = a
  1168. elif o in ('-?', '-h', '--help'):
  1169. self.do_help(['help', 'time'])
  1170. sys.exit(0)
  1171. elif o in ('-p', '--prefix'):
  1172. self.prefix = a
  1173. elif o in ('-t', '--tail'):
  1174. tail = int(a)
  1175. elif o in ('--title',):
  1176. self.title = a
  1177. elif o in ('--which',):
  1178. if not a in list(self.time_strings.keys()):
  1179. sys.stderr.write('%s: time: Unrecognized timer "%s".\n' % (self.name, a))
  1180. sys.stderr.write('%s Type "%s help time" for help.\n' % (self.name_spaces, self.name))
  1181. sys.exit(1)
  1182. which = a
  1183. if self.config_file:
  1184. HACK_for_exec(open(self.config_file, 'r').read(), self.__dict__)
  1185. if self.chdir:
  1186. os.chdir(self.chdir)
  1187. logfile_path = lambda x: os.path.join(self.chdir, x)
  1188. if not args:
  1189. pattern = '%s*.log' % self.prefix
  1190. args = self.args_to_files([pattern], tail)
  1191. if not args:
  1192. if self.chdir:
  1193. directory = self.chdir
  1194. else:
  1195. directory = os.getcwd()
  1196. sys.stderr.write('%s: time: No arguments specified.\n' % self.name)
  1197. sys.stderr.write('%s No %s*.log files found in "%s".\n' % (self.name_spaces, self.prefix, directory))
  1198. sys.stderr.write('%s Type "%s help time" for help.\n' % (self.name_spaces, self.name))
  1199. sys.exit(1)
  1200. else:
  1201. args = self.args_to_files(args, tail)
  1202. cwd_ = os.getcwd() + os.sep
  1203. if format == 'ascii':
  1204. columns = ("Total", "SConscripts", "SCons", "commands")
  1205. self.ascii_table(args, columns, self.get_debug_times, logfile_path)
  1206. elif format == 'gnuplot':
  1207. results = self.collect_results(args, self.get_debug_times,
  1208. self.time_strings[which])
  1209. self.gnuplot_results(results, fmt='%s %.6f')
  1210. else:
  1211. sys.stderr.write('%s: time: Unknown format "%s".\n' % (self.name, format))
  1212. sys.exit(1)
  1213. if __name__ == '__main__':
  1214. opts, args = getopt.getopt(sys.argv[1:], 'h?V', ['help', 'version'])
  1215. ST = SConsTimer()
  1216. for o, a in opts:
  1217. if o in ('-?', '-h', '--help'):
  1218. ST.do_help(['help'])
  1219. sys.exit(0)
  1220. elif o in ('-V', '--version'):
  1221. sys.stdout.write('scons-time version\n')
  1222. sys.exit(0)
  1223. if not args:
  1224. sys.stderr.write('Type "%s help" for usage.\n' % ST.name)
  1225. sys.exit(1)
  1226. ST.execute_subcommand(args)
  1227. # Local Variables:
  1228. # tab-width:4
  1229. # indent-tabs-mode:nil
  1230. # End:
  1231. # vim: set expandtab tabstop=4 shiftwidth=4: