bench.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422
  1. #!/usr/bin/env python3
  2. #
  3. # Script to compile and runs benches.
  4. #
  5. # Example:
  6. # ./scripts/bench.py runners/bench_runner -b
  7. #
  8. # Copyright (c) 2022, The littlefs authors.
  9. # SPDX-License-Identifier: BSD-3-Clause
  10. #
  11. import collections as co
  12. import csv
  13. import errno
  14. import glob
  15. import itertools as it
  16. import math as m
  17. import os
  18. import pty
  19. import re
  20. import shlex
  21. import shutil
  22. import signal
  23. import subprocess as sp
  24. import threading as th
  25. import time
  26. import toml
  27. RUNNER_PATH = './runners/bench_runner'
  28. HEADER_PATH = 'runners/bench_runner.h'
  29. GDB_TOOL = ['gdb']
  30. VALGRIND_TOOL = ['valgrind']
  31. PERF_SCRIPT = ['./scripts/perf.py']
  32. def openio(path, mode='r', buffering=-1):
  33. if path == '-':
  34. if mode == 'r':
  35. return os.fdopen(os.dup(sys.stdin.fileno()), mode, buffering)
  36. else:
  37. return os.fdopen(os.dup(sys.stdout.fileno()), mode, buffering)
  38. else:
  39. return open(path, mode, buffering)
  40. class BenchCase:
  41. # create a BenchCase object from a config
  42. def __init__(self, config, args={}):
  43. self.name = config.pop('name')
  44. self.path = config.pop('path')
  45. self.suite = config.pop('suite')
  46. self.lineno = config.pop('lineno', None)
  47. self.if_ = config.pop('if', None)
  48. if isinstance(self.if_, bool):
  49. self.if_ = 'true' if self.if_ else 'false'
  50. self.code = config.pop('code')
  51. self.code_lineno = config.pop('code_lineno', None)
  52. self.in_ = config.pop('in',
  53. config.pop('suite_in', None))
  54. # figure out defines and build possible permutations
  55. self.defines = set()
  56. self.permutations = []
  57. # defines can be a dict or a list or dicts
  58. suite_defines = config.pop('suite_defines', {})
  59. if not isinstance(suite_defines, list):
  60. suite_defines = [suite_defines]
  61. defines = config.pop('defines', {})
  62. if not isinstance(defines, list):
  63. defines = [defines]
  64. def csplit(v):
  65. # split commas but only outside of parens
  66. parens = 0
  67. i_ = 0
  68. for i in range(len(v)):
  69. if v[i] == ',' and parens == 0:
  70. yield v[i_:i]
  71. i_ = i+1
  72. elif v[i] in '([{':
  73. parens += 1
  74. elif v[i] in '}])':
  75. parens -= 1
  76. if v[i_:].strip():
  77. yield v[i_:]
  78. def parse_define(v):
  79. # a define entry can be a list
  80. if isinstance(v, list):
  81. for v_ in v:
  82. yield from parse_define(v_)
  83. # or a string
  84. elif isinstance(v, str):
  85. # which can be comma-separated values, with optional
  86. # range statements. This matches the runtime define parser in
  87. # the runner itself.
  88. for v_ in csplit(v):
  89. m = re.search(r'\brange\b\s*\('
  90. '(?P<start>[^,\s]*)'
  91. '\s*(?:,\s*(?P<stop>[^,\s]*)'
  92. '\s*(?:,\s*(?P<step>[^,\s]*)\s*)?)?\)',
  93. v_)
  94. if m:
  95. start = (int(m.group('start'), 0)
  96. if m.group('start') else 0)
  97. stop = (int(m.group('stop'), 0)
  98. if m.group('stop') else None)
  99. step = (int(m.group('step'), 0)
  100. if m.group('step') else 1)
  101. if m.lastindex <= 1:
  102. start, stop = 0, start
  103. for x in range(start, stop, step):
  104. yield from parse_define('%s(%d)%s' % (
  105. v_[:m.start()], x, v_[m.end():]))
  106. else:
  107. yield v_
  108. # or a literal value
  109. else:
  110. yield v
  111. # build possible permutations
  112. for suite_defines_ in suite_defines:
  113. self.defines |= suite_defines_.keys()
  114. for defines_ in defines:
  115. self.defines |= defines_.keys()
  116. self.permutations.extend(dict(perm) for perm in it.product(*(
  117. [(k, v) for v in parse_define(vs)]
  118. for k, vs in sorted((suite_defines_ | defines_).items()))))
  119. for k in config.keys():
  120. print('%swarning:%s in %s, found unused key %r' % (
  121. '\x1b[01;33m' if args['color'] else '',
  122. '\x1b[m' if args['color'] else '',
  123. self.name,
  124. k),
  125. file=sys.stderr)
  126. class BenchSuite:
  127. # create a BenchSuite object from a toml file
  128. def __init__(self, path, args={}):
  129. self.path = path
  130. self.name = os.path.basename(path)
  131. if self.name.endswith('.toml'):
  132. self.name = self.name[:-len('.toml')]
  133. # load toml file and parse bench cases
  134. with open(self.path) as f:
  135. # load benches
  136. config = toml.load(f)
  137. # find line numbers
  138. f.seek(0)
  139. case_linenos = []
  140. code_linenos = []
  141. for i, line in enumerate(f):
  142. match = re.match(
  143. '(?P<case>\[\s*cases\s*\.\s*(?P<name>\w+)\s*\])'
  144. '|' '(?P<code>code\s*=)',
  145. line)
  146. if match and match.group('case'):
  147. case_linenos.append((i+1, match.group('name')))
  148. elif match and match.group('code'):
  149. code_linenos.append(i+2)
  150. # sort in case toml parsing did not retain order
  151. case_linenos.sort()
  152. cases = config.pop('cases')
  153. for (lineno, name), (nlineno, _) in it.zip_longest(
  154. case_linenos, case_linenos[1:],
  155. fillvalue=(float('inf'), None)):
  156. code_lineno = min(
  157. (l for l in code_linenos if l >= lineno and l < nlineno),
  158. default=None)
  159. cases[name]['lineno'] = lineno
  160. cases[name]['code_lineno'] = code_lineno
  161. self.if_ = config.pop('if', None)
  162. if isinstance(self.if_, bool):
  163. self.if_ = 'true' if self.if_ else 'false'
  164. self.code = config.pop('code', None)
  165. self.code_lineno = min(
  166. (l for l in code_linenos
  167. if not case_linenos or l < case_linenos[0][0]),
  168. default=None)
  169. # a couple of these we just forward to all cases
  170. defines = config.pop('defines', {})
  171. in_ = config.pop('in', None)
  172. self.cases = []
  173. for name, case in sorted(cases.items(),
  174. key=lambda c: c[1].get('lineno')):
  175. self.cases.append(BenchCase(config={
  176. 'name': name,
  177. 'path': path + (':%d' % case['lineno']
  178. if 'lineno' in case else ''),
  179. 'suite': self.name,
  180. 'suite_defines': defines,
  181. 'suite_in': in_,
  182. **case},
  183. args=args))
  184. # combine per-case defines
  185. self.defines = set.union(*(
  186. set(case.defines) for case in self.cases))
  187. for k in config.keys():
  188. print('%swarning:%s in %s, found unused key %r' % (
  189. '\x1b[01;33m' if args['color'] else '',
  190. '\x1b[m' if args['color'] else '',
  191. self.name,
  192. k),
  193. file=sys.stderr)
  194. def compile(bench_paths, **args):
  195. # find .toml files
  196. paths = []
  197. for path in bench_paths:
  198. if os.path.isdir(path):
  199. path = path + '/*.toml'
  200. for path in glob.glob(path):
  201. paths.append(path)
  202. if not paths:
  203. print('no bench suites found in %r?' % bench_paths)
  204. sys.exit(-1)
  205. # load the suites
  206. suites = [BenchSuite(path, args) for path in paths]
  207. suites.sort(key=lambda s: s.name)
  208. # check for name conflicts, these will cause ambiguity problems later
  209. # when running benches
  210. seen = {}
  211. for suite in suites:
  212. if suite.name in seen:
  213. print('%swarning:%s conflicting suite %r, %s and %s' % (
  214. '\x1b[01;33m' if args['color'] else '',
  215. '\x1b[m' if args['color'] else '',
  216. suite.name,
  217. suite.path,
  218. seen[suite.name].path),
  219. file=sys.stderr)
  220. seen[suite.name] = suite
  221. for case in suite.cases:
  222. # only allow conflicts if a case and its suite share a name
  223. if case.name in seen and not (
  224. isinstance(seen[case.name], BenchSuite)
  225. and seen[case.name].cases == [case]):
  226. print('%swarning:%s conflicting case %r, %s and %s' % (
  227. '\x1b[01;33m' if args['color'] else '',
  228. '\x1b[m' if args['color'] else '',
  229. case.name,
  230. case.path,
  231. seen[case.name].path),
  232. file=sys.stderr)
  233. seen[case.name] = case
  234. # we can only compile one bench suite at a time
  235. if not args.get('source'):
  236. if len(suites) > 1:
  237. print('more than one bench suite for compilation? (%r)' % bench_paths)
  238. sys.exit(-1)
  239. suite = suites[0]
  240. # write generated bench source
  241. if 'output' in args:
  242. with openio(args['output'], 'w') as f:
  243. _write = f.write
  244. def write(s):
  245. f.lineno += s.count('\n')
  246. _write(s)
  247. def writeln(s=''):
  248. f.lineno += s.count('\n') + 1
  249. _write(s)
  250. _write('\n')
  251. f.lineno = 1
  252. f.write = write
  253. f.writeln = writeln
  254. f.writeln("// Generated by %s:" % sys.argv[0])
  255. f.writeln("//")
  256. f.writeln("// %s" % ' '.join(sys.argv))
  257. f.writeln("//")
  258. f.writeln()
  259. # include bench_runner.h in every generated file
  260. f.writeln("#include \"%s\"" % args['include'])
  261. f.writeln()
  262. # write out generated functions, this can end up in different
  263. # files depending on the "in" attribute
  264. #
  265. # note it's up to the specific generated file to declare
  266. # the bench defines
  267. def write_case_functions(f, suite, case):
  268. # create case define functions
  269. if case.defines:
  270. # deduplicate defines by value to try to reduce the
  271. # number of functions we generate
  272. define_cbs = {}
  273. for i, defines in enumerate(case.permutations):
  274. for k, v in sorted(defines.items()):
  275. if v not in define_cbs:
  276. name = ('__bench__%s__%s__%s__%d'
  277. % (suite.name, case.name, k, i))
  278. define_cbs[v] = name
  279. f.writeln('intmax_t %s('
  280. '__attribute__((unused)) '
  281. 'void *data) {' % name)
  282. f.writeln(4*' '+'return %s;' % v)
  283. f.writeln('}')
  284. f.writeln()
  285. f.writeln('const bench_define_t '
  286. '__bench__%s__%s__defines[]['
  287. 'BENCH_IMPLICIT_DEFINE_COUNT+%d] = {'
  288. % (suite.name, case.name, len(suite.defines)))
  289. for defines in case.permutations:
  290. f.writeln(4*' '+'{')
  291. for k, v in sorted(defines.items()):
  292. f.writeln(8*' '+'[%-24s] = {%s, NULL},' % (
  293. k+'_i', define_cbs[v]))
  294. f.writeln(4*' '+'},')
  295. f.writeln('};')
  296. f.writeln()
  297. # create case filter function
  298. if suite.if_ is not None or case.if_ is not None:
  299. f.writeln('bool __bench__%s__%s__filter(void) {'
  300. % (suite.name, case.name))
  301. f.writeln(4*' '+'return %s;'
  302. % ' && '.join('(%s)' % if_
  303. for if_ in [suite.if_, case.if_]
  304. if if_ is not None))
  305. f.writeln('}')
  306. f.writeln()
  307. # create case run function
  308. f.writeln('void __bench__%s__%s__run('
  309. '__attribute__((unused)) struct lfs_config *cfg) {'
  310. % (suite.name, case.name))
  311. f.writeln(4*' '+'// bench case %s' % case.name)
  312. if case.code_lineno is not None:
  313. f.writeln(4*' '+'#line %d "%s"'
  314. % (case.code_lineno, suite.path))
  315. f.write(case.code)
  316. if case.code_lineno is not None:
  317. f.writeln(4*' '+'#line %d "%s"'
  318. % (f.lineno+1, args['output']))
  319. f.writeln('}')
  320. f.writeln()
  321. if not args.get('source'):
  322. if suite.code is not None:
  323. if suite.code_lineno is not None:
  324. f.writeln('#line %d "%s"'
  325. % (suite.code_lineno, suite.path))
  326. f.write(suite.code)
  327. if suite.code_lineno is not None:
  328. f.writeln('#line %d "%s"'
  329. % (f.lineno+1, args['output']))
  330. f.writeln()
  331. if suite.defines:
  332. for i, define in enumerate(sorted(suite.defines)):
  333. f.writeln('#ifndef %s' % define)
  334. f.writeln('#define %-24s '
  335. 'BENCH_IMPLICIT_DEFINE_COUNT+%d' % (define+'_i', i))
  336. f.writeln('#define %-24s '
  337. 'BENCH_DEFINE(%s)' % (define, define+'_i'))
  338. f.writeln('#endif')
  339. f.writeln()
  340. # create case functions
  341. for case in suite.cases:
  342. if case.in_ is None:
  343. write_case_functions(f, suite, case)
  344. else:
  345. if case.defines:
  346. f.writeln('extern const bench_define_t '
  347. '__bench__%s__%s__defines[]['
  348. 'BENCH_IMPLICIT_DEFINE_COUNT+%d];'
  349. % (suite.name, case.name, len(suite.defines)))
  350. if suite.if_ is not None or case.if_ is not None:
  351. f.writeln('extern bool __bench__%s__%s__filter('
  352. 'void);'
  353. % (suite.name, case.name))
  354. f.writeln('extern void __bench__%s__%s__run('
  355. 'struct lfs_config *cfg);'
  356. % (suite.name, case.name))
  357. f.writeln()
  358. # create suite struct
  359. #
  360. # note we place this in the custom bench_suites section with
  361. # minimum alignment, otherwise GCC ups the alignment to
  362. # 32-bytes for some reason
  363. f.writeln('__attribute__((section("_bench_suites"), '
  364. 'aligned(1)))')
  365. f.writeln('const struct bench_suite __bench__%s__suite = {'
  366. % suite.name)
  367. f.writeln(4*' '+'.name = "%s",' % suite.name)
  368. f.writeln(4*' '+'.path = "%s",' % suite.path)
  369. f.writeln(4*' '+'.flags = 0,')
  370. if suite.defines:
  371. # create suite define names
  372. f.writeln(4*' '+'.define_names = (const char *const['
  373. 'BENCH_IMPLICIT_DEFINE_COUNT+%d]){' % (
  374. len(suite.defines)))
  375. for k in sorted(suite.defines):
  376. f.writeln(8*' '+'[%-24s] = "%s",' % (k+'_i', k))
  377. f.writeln(4*' '+'},')
  378. f.writeln(4*' '+'.define_count = '
  379. 'BENCH_IMPLICIT_DEFINE_COUNT+%d,' % len(suite.defines))
  380. f.writeln(4*' '+'.cases = (const struct bench_case[]){')
  381. for case in suite.cases:
  382. # create case structs
  383. f.writeln(8*' '+'{')
  384. f.writeln(12*' '+'.name = "%s",' % case.name)
  385. f.writeln(12*' '+'.path = "%s",' % case.path)
  386. f.writeln(12*' '+'.flags = 0,')
  387. f.writeln(12*' '+'.permutations = %d,'
  388. % len(case.permutations))
  389. if case.defines:
  390. f.writeln(12*' '+'.defines '
  391. '= (const bench_define_t*)__bench__%s__%s__defines,'
  392. % (suite.name, case.name))
  393. if suite.if_ is not None or case.if_ is not None:
  394. f.writeln(12*' '+'.filter = __bench__%s__%s__filter,'
  395. % (suite.name, case.name))
  396. f.writeln(12*' '+'.run = __bench__%s__%s__run,'
  397. % (suite.name, case.name))
  398. f.writeln(8*' '+'},')
  399. f.writeln(4*' '+'},')
  400. f.writeln(4*' '+'.case_count = %d,' % len(suite.cases))
  401. f.writeln('};')
  402. f.writeln()
  403. else:
  404. # copy source
  405. f.writeln('#line 1 "%s"' % args['source'])
  406. with open(args['source']) as sf:
  407. shutil.copyfileobj(sf, f)
  408. f.writeln()
  409. # write any internal benches
  410. for suite in suites:
  411. for case in suite.cases:
  412. if (case.in_ is not None
  413. and os.path.normpath(case.in_)
  414. == os.path.normpath(args['source'])):
  415. # write defines, but note we need to undef any
  416. # new defines since we're in someone else's file
  417. if suite.defines:
  418. for i, define in enumerate(
  419. sorted(suite.defines)):
  420. f.writeln('#ifndef %s' % define)
  421. f.writeln('#define %-24s '
  422. 'BENCH_IMPLICIT_DEFINE_COUNT+%d' % (
  423. define+'_i', i))
  424. f.writeln('#define %-24s '
  425. 'BENCH_DEFINE(%s)' % (
  426. define, define+'_i'))
  427. f.writeln('#define '
  428. '__BENCH__%s__NEEDS_UNDEF' % (
  429. define))
  430. f.writeln('#endif')
  431. f.writeln()
  432. write_case_functions(f, suite, case)
  433. if suite.defines:
  434. for define in sorted(suite.defines):
  435. f.writeln('#ifdef __BENCH__%s__NEEDS_UNDEF'
  436. % define)
  437. f.writeln('#undef __BENCH__%s__NEEDS_UNDEF'
  438. % define)
  439. f.writeln('#undef %s' % define)
  440. f.writeln('#undef %s' % (define+'_i'))
  441. f.writeln('#endif')
  442. f.writeln()
  443. def find_runner(runner, **args):
  444. cmd = runner.copy()
  445. # run under some external command?
  446. if args.get('exec'):
  447. cmd[:0] = args['exec']
  448. # run under valgrind?
  449. if args.get('valgrind'):
  450. cmd[:0] = args['valgrind_tool'] + [
  451. '--leak-check=full',
  452. '--track-origins=yes',
  453. '--error-exitcode=4',
  454. '-q']
  455. # run under perf?
  456. if args.get('perf'):
  457. cmd[:0] = args['perf_script'] + list(filter(None, [
  458. '-R',
  459. '--perf-freq=%s' % args['perf_freq']
  460. if args.get('perf_freq') else None,
  461. '--perf-period=%s' % args['perf_period']
  462. if args.get('perf_period') else None,
  463. '--perf-events=%s' % args['perf_events']
  464. if args.get('perf_events') else None,
  465. '--perf-tool=%s' % args['perf_tool']
  466. if args.get('perf_tool') else None,
  467. '-o%s' % args['perf']]))
  468. # other context
  469. if args.get('geometry'):
  470. cmd.append('-G%s' % args['geometry'])
  471. if args.get('disk'):
  472. cmd.append('-d%s' % args['disk'])
  473. if args.get('trace'):
  474. cmd.append('-t%s' % args['trace'])
  475. if args.get('trace_backtrace'):
  476. cmd.append('--trace-backtrace')
  477. if args.get('trace_period'):
  478. cmd.append('--trace-period=%s' % args['trace_period'])
  479. if args.get('trace_freq'):
  480. cmd.append('--trace-freq=%s' % args['trace_freq'])
  481. if args.get('read_sleep'):
  482. cmd.append('--read-sleep=%s' % args['read_sleep'])
  483. if args.get('prog_sleep'):
  484. cmd.append('--prog-sleep=%s' % args['prog_sleep'])
  485. if args.get('erase_sleep'):
  486. cmd.append('--erase-sleep=%s' % args['erase_sleep'])
  487. # defines?
  488. if args.get('define'):
  489. for define in args.get('define'):
  490. cmd.append('-D%s' % define)
  491. return cmd
  492. def list_(runner, bench_ids=[], **args):
  493. cmd = find_runner(runner, **args) + bench_ids
  494. if args.get('summary'): cmd.append('--summary')
  495. if args.get('list_suites'): cmd.append('--list-suites')
  496. if args.get('list_cases'): cmd.append('--list-cases')
  497. if args.get('list_suite_paths'): cmd.append('--list-suite-paths')
  498. if args.get('list_case_paths'): cmd.append('--list-case-paths')
  499. if args.get('list_defines'): cmd.append('--list-defines')
  500. if args.get('list_permutation_defines'):
  501. cmd.append('--list-permutation-defines')
  502. if args.get('list_implicit_defines'):
  503. cmd.append('--list-implicit-defines')
  504. if args.get('list_geometries'): cmd.append('--list-geometries')
  505. if args.get('verbose'):
  506. print(' '.join(shlex.quote(c) for c in cmd))
  507. return sp.call(cmd)
  508. def find_perms(runner_, ids=[], **args):
  509. case_suites = {}
  510. expected_case_perms = co.defaultdict(lambda: 0)
  511. expected_perms = 0
  512. total_perms = 0
  513. # query cases from the runner
  514. cmd = runner_ + ['--list-cases'] + ids
  515. if args.get('verbose'):
  516. print(' '.join(shlex.quote(c) for c in cmd))
  517. proc = sp.Popen(cmd,
  518. stdout=sp.PIPE,
  519. stderr=sp.PIPE if not args.get('verbose') else None,
  520. universal_newlines=True,
  521. errors='replace',
  522. close_fds=False)
  523. pattern = re.compile(
  524. '^(?P<case>[^\s]+)'
  525. '\s+(?P<flags>[^\s]+)'
  526. '\s+(?P<filtered>\d+)/(?P<perms>\d+)')
  527. # skip the first line
  528. for line in it.islice(proc.stdout, 1, None):
  529. m = pattern.match(line)
  530. if m:
  531. filtered = int(m.group('filtered'))
  532. perms = int(m.group('perms'))
  533. expected_case_perms[m.group('case')] += filtered
  534. expected_perms += filtered
  535. total_perms += perms
  536. proc.wait()
  537. if proc.returncode != 0:
  538. if not args.get('verbose'):
  539. for line in proc.stderr:
  540. sys.stdout.write(line)
  541. sys.exit(-1)
  542. # get which suite each case belongs to via paths
  543. cmd = runner_ + ['--list-case-paths'] + ids
  544. if args.get('verbose'):
  545. print(' '.join(shlex.quote(c) for c in cmd))
  546. proc = sp.Popen(cmd,
  547. stdout=sp.PIPE,
  548. stderr=sp.PIPE if not args.get('verbose') else None,
  549. universal_newlines=True,
  550. errors='replace',
  551. close_fds=False)
  552. pattern = re.compile(
  553. '^(?P<case>[^\s]+)'
  554. '\s+(?P<path>[^:]+):(?P<lineno>\d+)')
  555. # skip the first line
  556. for line in it.islice(proc.stdout, 1, None):
  557. m = pattern.match(line)
  558. if m:
  559. path = m.group('path')
  560. # strip path/suffix here
  561. suite = os.path.basename(path)
  562. if suite.endswith('.toml'):
  563. suite = suite[:-len('.toml')]
  564. case_suites[m.group('case')] = suite
  565. proc.wait()
  566. if proc.returncode != 0:
  567. if not args.get('verbose'):
  568. for line in proc.stderr:
  569. sys.stdout.write(line)
  570. sys.exit(-1)
  571. # figure out expected suite perms
  572. expected_suite_perms = co.defaultdict(lambda: 0)
  573. for case, suite in case_suites.items():
  574. expected_suite_perms[suite] += expected_case_perms[case]
  575. return (
  576. case_suites,
  577. expected_suite_perms,
  578. expected_case_perms,
  579. expected_perms,
  580. total_perms)
  581. def find_path(runner_, id, **args):
  582. path = None
  583. # query from runner
  584. cmd = runner_ + ['--list-case-paths', id]
  585. if args.get('verbose'):
  586. print(' '.join(shlex.quote(c) for c in cmd))
  587. proc = sp.Popen(cmd,
  588. stdout=sp.PIPE,
  589. stderr=sp.PIPE if not args.get('verbose') else None,
  590. universal_newlines=True,
  591. errors='replace',
  592. close_fds=False)
  593. pattern = re.compile(
  594. '^(?P<case>[^\s]+)'
  595. '\s+(?P<path>[^:]+):(?P<lineno>\d+)')
  596. # skip the first line
  597. for line in it.islice(proc.stdout, 1, None):
  598. m = pattern.match(line)
  599. if m and path is None:
  600. path_ = m.group('path')
  601. lineno = int(m.group('lineno'))
  602. path = (path_, lineno)
  603. proc.wait()
  604. if proc.returncode != 0:
  605. if not args.get('verbose'):
  606. for line in proc.stderr:
  607. sys.stdout.write(line)
  608. sys.exit(-1)
  609. return path
  610. def find_defines(runner_, id, **args):
  611. # query permutation defines from runner
  612. cmd = runner_ + ['--list-permutation-defines', id]
  613. if args.get('verbose'):
  614. print(' '.join(shlex.quote(c) for c in cmd))
  615. proc = sp.Popen(cmd,
  616. stdout=sp.PIPE,
  617. stderr=sp.PIPE if not args.get('verbose') else None,
  618. universal_newlines=True,
  619. errors='replace',
  620. close_fds=False)
  621. defines = co.OrderedDict()
  622. pattern = re.compile('^(?P<define>\w+)=(?P<value>.+)')
  623. for line in proc.stdout:
  624. m = pattern.match(line)
  625. if m:
  626. define = m.group('define')
  627. value = m.group('value')
  628. defines[define] = value
  629. proc.wait()
  630. if proc.returncode != 0:
  631. if not args.get('verbose'):
  632. for line in proc.stderr:
  633. sys.stdout.write(line)
  634. sys.exit(-1)
  635. return defines
  636. # Thread-safe CSV writer
  637. class BenchOutput:
  638. def __init__(self, path, head=None, tail=None):
  639. self.f = openio(path, 'w+', 1)
  640. self.lock = th.Lock()
  641. self.head = head or []
  642. self.tail = tail or []
  643. self.writer = csv.DictWriter(self.f, self.head + self.tail)
  644. self.rows = []
  645. def close(self):
  646. self.f.close()
  647. def __enter__(self):
  648. return self
  649. def __exit__(self, *_):
  650. self.f.close()
  651. def writerow(self, row):
  652. with self.lock:
  653. self.rows.append(row)
  654. if all(k in self.head or k in self.tail for k in row.keys()):
  655. # can simply append
  656. self.writer.writerow(row)
  657. else:
  658. # need to rewrite the file
  659. self.head.extend(row.keys() - (self.head + self.tail))
  660. self.f.seek(0)
  661. self.f.truncate()
  662. self.writer = csv.DictWriter(self.f, self.head + self.tail)
  663. self.writer.writeheader()
  664. for row in self.rows:
  665. self.writer.writerow(row)
  666. # A bench failure
  667. class BenchFailure(Exception):
  668. def __init__(self, id, returncode, stdout, assert_=None):
  669. self.id = id
  670. self.returncode = returncode
  671. self.stdout = stdout
  672. self.assert_ = assert_
  673. def run_stage(name, runner_, ids, stdout_, trace_, output_, **args):
  674. # get expected suite/case/perm counts
  675. (case_suites,
  676. expected_suite_perms,
  677. expected_case_perms,
  678. expected_perms,
  679. total_perms) = find_perms(runner_, ids, **args)
  680. passed_suite_perms = co.defaultdict(lambda: 0)
  681. passed_case_perms = co.defaultdict(lambda: 0)
  682. passed_perms = 0
  683. readed = 0
  684. proged = 0
  685. erased = 0
  686. failures = []
  687. killed = False
  688. pattern = re.compile('^(?:'
  689. '(?P<op>running|finished|skipped|powerloss)'
  690. ' (?P<id>(?P<case>[^:]+)[^\s]*)'
  691. '(?: (?P<readed>\d+))?'
  692. '(?: (?P<proged>\d+))?'
  693. '(?: (?P<erased>\d+))?'
  694. '|' '(?P<path>[^:]+):(?P<lineno>\d+):(?P<op_>assert):'
  695. ' *(?P<message>.*)'
  696. ')$')
  697. locals = th.local()
  698. children = set()
  699. def run_runner(runner_, ids=[]):
  700. nonlocal passed_suite_perms
  701. nonlocal passed_case_perms
  702. nonlocal passed_perms
  703. nonlocal readed
  704. nonlocal proged
  705. nonlocal erased
  706. nonlocal locals
  707. # run the benches!
  708. cmd = runner_ + ids
  709. if args.get('verbose'):
  710. print(' '.join(shlex.quote(c) for c in cmd))
  711. mpty, spty = pty.openpty()
  712. proc = sp.Popen(cmd, stdout=spty, stderr=spty, close_fds=False)
  713. os.close(spty)
  714. children.add(proc)
  715. mpty = os.fdopen(mpty, 'r', 1)
  716. last_id = None
  717. last_stdout = []
  718. last_assert = None
  719. try:
  720. while True:
  721. # parse a line for state changes
  722. try:
  723. line = mpty.readline()
  724. except OSError as e:
  725. if e.errno != errno.EIO:
  726. raise
  727. break
  728. if not line:
  729. break
  730. last_stdout.append(line)
  731. if stdout_:
  732. try:
  733. stdout_.write(line)
  734. stdout_.flush()
  735. except BrokenPipeError:
  736. pass
  737. if args.get('verbose'):
  738. sys.stdout.write(line)
  739. m = pattern.match(line)
  740. if m:
  741. op = m.group('op') or m.group('op_')
  742. if op == 'running':
  743. locals.seen_perms += 1
  744. last_id = m.group('id')
  745. last_stdout = []
  746. last_assert = None
  747. elif op == 'finished':
  748. case = m.group('case')
  749. suite = case_suites[case]
  750. readed_ = int(m.group('readed'))
  751. proged_ = int(m.group('proged'))
  752. erased_ = int(m.group('erased'))
  753. passed_suite_perms[suite] += 1
  754. passed_case_perms[case] += 1
  755. passed_perms += 1
  756. readed += readed_
  757. proged += proged_
  758. erased += erased_
  759. if output_:
  760. # get defines and write to csv
  761. defines = find_defines(
  762. runner_, m.group('id'), **args)
  763. output_.writerow({
  764. 'suite': suite,
  765. 'case': case,
  766. 'bench_readed': readed_,
  767. 'bench_proged': proged_,
  768. 'bench_erased': erased_,
  769. **defines})
  770. elif op == 'skipped':
  771. locals.seen_perms += 1
  772. elif op == 'assert':
  773. last_assert = (
  774. m.group('path'),
  775. int(m.group('lineno')),
  776. m.group('message'))
  777. # go ahead and kill the process, aborting takes a while
  778. if args.get('keep_going'):
  779. proc.kill()
  780. except KeyboardInterrupt:
  781. raise BenchFailure(last_id, 1, last_stdout)
  782. finally:
  783. children.remove(proc)
  784. mpty.close()
  785. proc.wait()
  786. if proc.returncode != 0:
  787. raise BenchFailure(
  788. last_id,
  789. proc.returncode,
  790. last_stdout,
  791. last_assert)
  792. def run_job(runner_, ids=[], start=None, step=None):
  793. nonlocal failures
  794. nonlocal killed
  795. nonlocal locals
  796. start = start or 0
  797. step = step or 1
  798. while start < total_perms:
  799. job_runner = runner_.copy()
  800. if args.get('isolate') or args.get('valgrind'):
  801. job_runner.append('-s%s,%s,%s' % (start, start+step, step))
  802. else:
  803. job_runner.append('-s%s,,%s' % (start, step))
  804. try:
  805. # run the benches
  806. locals.seen_perms = 0
  807. run_runner(job_runner, ids)
  808. assert locals.seen_perms > 0
  809. start += locals.seen_perms*step
  810. except BenchFailure as failure:
  811. # keep track of failures
  812. if output_:
  813. case, _ = failure.id.split(':', 1)
  814. suite = case_suites[case]
  815. # get defines and write to csv
  816. defines = find_defines(runner_, failure.id, **args)
  817. output_.writerow({
  818. 'suite': suite,
  819. 'case': case,
  820. **defines})
  821. # race condition for multiple failures?
  822. if failures and not args.get('keep_going'):
  823. break
  824. failures.append(failure)
  825. if args.get('keep_going') and not killed:
  826. # resume after failed bench
  827. assert locals.seen_perms > 0
  828. start += locals.seen_perms*step
  829. continue
  830. else:
  831. # stop other benches
  832. killed = True
  833. for child in children.copy():
  834. child.kill()
  835. break
  836. # parallel jobs?
  837. runners = []
  838. if 'jobs' in args:
  839. for job in range(args['jobs']):
  840. runners.append(th.Thread(
  841. target=run_job, args=(runner_, ids, job, args['jobs']),
  842. daemon=True))
  843. else:
  844. runners.append(th.Thread(
  845. target=run_job, args=(runner_, ids, None, None),
  846. daemon=True))
  847. def print_update(done):
  848. if not args.get('verbose') and (args['color'] or done):
  849. sys.stdout.write('%s%srunning %s%s:%s %s%s' % (
  850. '\r\x1b[K' if args['color'] else '',
  851. '\x1b[?7l' if not done else '',
  852. ('\x1b[34m' if not failures else '\x1b[31m')
  853. if args['color'] else '',
  854. name,
  855. '\x1b[m' if args['color'] else '',
  856. ', '.join(filter(None, [
  857. '%d/%d suites' % (
  858. sum(passed_suite_perms[k] == v
  859. for k, v in expected_suite_perms.items()),
  860. len(expected_suite_perms))
  861. if (not args.get('by_suites')
  862. and not args.get('by_cases')) else None,
  863. '%d/%d cases' % (
  864. sum(passed_case_perms[k] == v
  865. for k, v in expected_case_perms.items()),
  866. len(expected_case_perms))
  867. if not args.get('by_cases') else None,
  868. '%d/%d perms' % (passed_perms, expected_perms),
  869. '%s%d/%d failures%s' % (
  870. '\x1b[31m' if args['color'] else '',
  871. len(failures),
  872. expected_perms,
  873. '\x1b[m' if args['color'] else '')
  874. if failures else None])),
  875. '\x1b[?7h' if not done else '\n'))
  876. sys.stdout.flush()
  877. for r in runners:
  878. r.start()
  879. try:
  880. while any(r.is_alive() for r in runners):
  881. time.sleep(0.01)
  882. print_update(False)
  883. except KeyboardInterrupt:
  884. # this is handled by the runner threads, we just
  885. # need to not abort here
  886. killed = True
  887. finally:
  888. print_update(True)
  889. for r in runners:
  890. r.join()
  891. return (
  892. expected_perms,
  893. passed_perms,
  894. readed,
  895. proged,
  896. erased,
  897. failures,
  898. killed)
  899. def run(runner, bench_ids=[], **args):
  900. # query runner for benches
  901. runner_ = find_runner(runner, **args)
  902. print('using runner: %s' % ' '.join(shlex.quote(c) for c in runner_))
  903. (_,
  904. expected_suite_perms,
  905. expected_case_perms,
  906. expected_perms,
  907. total_perms) = find_perms(runner_, bench_ids, **args)
  908. print('found %d suites, %d cases, %d/%d permutations' % (
  909. len(expected_suite_perms),
  910. len(expected_case_perms),
  911. expected_perms,
  912. total_perms))
  913. print()
  914. # automatic job detection?
  915. if args.get('jobs') == 0:
  916. args['jobs'] = len(os.sched_getaffinity(0))
  917. # truncate and open logs here so they aren't disconnected between benches
  918. stdout = None
  919. if args.get('stdout'):
  920. stdout = openio(args['stdout'], 'w', 1)
  921. trace = None
  922. if args.get('trace'):
  923. trace = openio(args['trace'], 'w', 1)
  924. output = None
  925. if args.get('output'):
  926. output = BenchOutput(args['output'],
  927. ['suite', 'case'],
  928. ['bench_readed', 'bench_proged', 'bench_erased'])
  929. # measure runtime
  930. start = time.time()
  931. # spawn runners
  932. expected = 0
  933. passed = 0
  934. readed = 0
  935. proged = 0
  936. erased = 0
  937. failures = []
  938. for by in (expected_case_perms.keys() if args.get('by_cases')
  939. else expected_suite_perms.keys() if args.get('by_suites')
  940. else [None]):
  941. # spawn jobs for stage
  942. (expected_,
  943. passed_,
  944. readed_,
  945. proged_,
  946. erased_,
  947. failures_,
  948. killed) = run_stage(
  949. by or 'benches',
  950. runner_,
  951. [by] if by is not None else bench_ids,
  952. stdout,
  953. trace,
  954. output,
  955. **args)
  956. # collect passes/failures
  957. expected += expected_
  958. passed += passed_
  959. readed += readed_
  960. proged += proged_
  961. erased += erased_
  962. failures.extend(failures_)
  963. if (failures and not args.get('keep_going')) or killed:
  964. break
  965. stop = time.time()
  966. if stdout:
  967. try:
  968. stdout.close()
  969. except BrokenPipeError:
  970. pass
  971. if trace:
  972. try:
  973. trace.close()
  974. except BrokenPipeError:
  975. pass
  976. if output:
  977. output.close()
  978. # show summary
  979. print()
  980. print('%sdone:%s %s' % (
  981. ('\x1b[34m' if not failures else '\x1b[31m')
  982. if args['color'] else '',
  983. '\x1b[m' if args['color'] else '',
  984. ', '.join(filter(None, [
  985. '%d readed' % readed,
  986. '%d proged' % proged,
  987. '%d erased' % erased,
  988. 'in %.2fs' % (stop-start)]))))
  989. print()
  990. # print each failure
  991. for failure in failures:
  992. assert failure.id is not None, '%s broken? %r' % (
  993. ' '.join(shlex.quote(c) for c in runner_),
  994. failure)
  995. # get some extra info from runner
  996. path, lineno = find_path(runner_, failure.id, **args)
  997. defines = find_defines(runner_, failure.id, **args)
  998. # show summary of failure
  999. print('%s%s:%d:%sfailure:%s %s%s failed' % (
  1000. '\x1b[01m' if args['color'] else '',
  1001. path, lineno,
  1002. '\x1b[01;31m' if args['color'] else '',
  1003. '\x1b[m' if args['color'] else '',
  1004. failure.id,
  1005. ' (%s)' % ', '.join('%s=%s' % (k,v) for k,v in defines.items())
  1006. if defines else ''))
  1007. if failure.stdout:
  1008. stdout = failure.stdout
  1009. if failure.assert_ is not None:
  1010. stdout = stdout[:-1]
  1011. for line in stdout[-args.get('context', 5):]:
  1012. sys.stdout.write(line)
  1013. if failure.assert_ is not None:
  1014. path, lineno, message = failure.assert_
  1015. print('%s%s:%d:%sassert:%s %s' % (
  1016. '\x1b[01m' if args['color'] else '',
  1017. path, lineno,
  1018. '\x1b[01;31m' if args['color'] else '',
  1019. '\x1b[m' if args['color'] else '',
  1020. message))
  1021. with open(path) as f:
  1022. line = next(it.islice(f, lineno-1, None)).strip('\n')
  1023. print(line)
  1024. print()
  1025. # drop into gdb?
  1026. if failures and (args.get('gdb')
  1027. or args.get('gdb_case')
  1028. or args.get('gdb_main')):
  1029. failure = failures[0]
  1030. cmd = runner_ + [failure.id]
  1031. if args.get('gdb_main'):
  1032. cmd[:0] = args['gdb_tool'] + [
  1033. '-ex', 'break main',
  1034. '-ex', 'run',
  1035. '--args']
  1036. elif args.get('gdb_case'):
  1037. path, lineno = find_path(runner_, failure.id, **args)
  1038. cmd[:0] = args['gdb_tool'] + [
  1039. '-ex', 'break %s:%d' % (path, lineno),
  1040. '-ex', 'run',
  1041. '--args']
  1042. elif failure.assert_ is not None:
  1043. cmd[:0] = args['gdb_tool'] + [
  1044. '-ex', 'run',
  1045. '-ex', 'frame function raise',
  1046. '-ex', 'up 2',
  1047. '--args']
  1048. else:
  1049. cmd[:0] = args['gdb_tool'] + [
  1050. '-ex', 'run',
  1051. '--args']
  1052. # exec gdb interactively
  1053. if args.get('verbose'):
  1054. print(' '.join(shlex.quote(c) for c in cmd))
  1055. os.execvp(cmd[0], cmd)
  1056. return 1 if failures else 0
  1057. def main(**args):
  1058. # figure out what color should be
  1059. if args.get('color') == 'auto':
  1060. args['color'] = sys.stdout.isatty()
  1061. elif args.get('color') == 'always':
  1062. args['color'] = True
  1063. else:
  1064. args['color'] = False
  1065. if args.get('compile'):
  1066. return compile(**args)
  1067. elif (args.get('summary')
  1068. or args.get('list_suites')
  1069. or args.get('list_cases')
  1070. or args.get('list_suite_paths')
  1071. or args.get('list_case_paths')
  1072. or args.get('list_defines')
  1073. or args.get('list_permutation_defines')
  1074. or args.get('list_implicit_defines')
  1075. or args.get('list_geometries')):
  1076. return list_(**args)
  1077. else:
  1078. return run(**args)
  1079. if __name__ == "__main__":
  1080. import argparse
  1081. import sys
  1082. argparse.ArgumentParser._handle_conflict_ignore = lambda *_: None
  1083. argparse._ArgumentGroup._handle_conflict_ignore = lambda *_: None
  1084. parser = argparse.ArgumentParser(
  1085. description="Build and run benches.",
  1086. allow_abbrev=False,
  1087. conflict_handler='ignore')
  1088. parser.add_argument(
  1089. '-v', '--verbose',
  1090. action='store_true',
  1091. help="Output commands that run behind the scenes.")
  1092. parser.add_argument(
  1093. '--color',
  1094. choices=['never', 'always', 'auto'],
  1095. default='auto',
  1096. help="When to use terminal colors. Defaults to 'auto'.")
  1097. # bench flags
  1098. bench_parser = parser.add_argument_group('bench options')
  1099. bench_parser.add_argument(
  1100. 'runner',
  1101. nargs='?',
  1102. type=lambda x: x.split(),
  1103. help="Bench runner to use for benching. Defaults to %r." % RUNNER_PATH)
  1104. bench_parser.add_argument(
  1105. 'bench_ids',
  1106. nargs='*',
  1107. help="Description of benches to run.")
  1108. bench_parser.add_argument(
  1109. '-Y', '--summary',
  1110. action='store_true',
  1111. help="Show quick summary.")
  1112. bench_parser.add_argument(
  1113. '-l', '--list-suites',
  1114. action='store_true',
  1115. help="List bench suites.")
  1116. bench_parser.add_argument(
  1117. '-L', '--list-cases',
  1118. action='store_true',
  1119. help="List bench cases.")
  1120. bench_parser.add_argument(
  1121. '--list-suite-paths',
  1122. action='store_true',
  1123. help="List the path for each bench suite.")
  1124. bench_parser.add_argument(
  1125. '--list-case-paths',
  1126. action='store_true',
  1127. help="List the path and line number for each bench case.")
  1128. bench_parser.add_argument(
  1129. '--list-defines',
  1130. action='store_true',
  1131. help="List all defines in this bench-runner.")
  1132. bench_parser.add_argument(
  1133. '--list-permutation-defines',
  1134. action='store_true',
  1135. help="List explicit defines in this bench-runner.")
  1136. bench_parser.add_argument(
  1137. '--list-implicit-defines',
  1138. action='store_true',
  1139. help="List implicit defines in this bench-runner.")
  1140. bench_parser.add_argument(
  1141. '--list-geometries',
  1142. action='store_true',
  1143. help="List the available disk geometries.")
  1144. bench_parser.add_argument(
  1145. '-D', '--define',
  1146. action='append',
  1147. help="Override a bench define.")
  1148. bench_parser.add_argument(
  1149. '-G', '--geometry',
  1150. help="Comma-separated list of disk geometries to bench.")
  1151. bench_parser.add_argument(
  1152. '-d', '--disk',
  1153. help="Direct block device operations to this file.")
  1154. bench_parser.add_argument(
  1155. '-t', '--trace',
  1156. help="Direct trace output to this file.")
  1157. bench_parser.add_argument(
  1158. '--trace-backtrace',
  1159. action='store_true',
  1160. help="Include a backtrace with every trace statement.")
  1161. bench_parser.add_argument(
  1162. '--trace-period',
  1163. help="Sample trace output at this period in cycles.")
  1164. bench_parser.add_argument(
  1165. '--trace-freq',
  1166. help="Sample trace output at this frequency in hz.")
  1167. bench_parser.add_argument(
  1168. '-O', '--stdout',
  1169. help="Direct stdout to this file. Note stderr is already merged here.")
  1170. bench_parser.add_argument(
  1171. '-o', '--output',
  1172. help="CSV file to store results.")
  1173. bench_parser.add_argument(
  1174. '--read-sleep',
  1175. help="Artificial read delay in seconds.")
  1176. bench_parser.add_argument(
  1177. '--prog-sleep',
  1178. help="Artificial prog delay in seconds.")
  1179. bench_parser.add_argument(
  1180. '--erase-sleep',
  1181. help="Artificial erase delay in seconds.")
  1182. bench_parser.add_argument(
  1183. '-j', '--jobs',
  1184. nargs='?',
  1185. type=lambda x: int(x, 0),
  1186. const=0,
  1187. help="Number of parallel runners to run. 0 runs one runner per core.")
  1188. bench_parser.add_argument(
  1189. '-k', '--keep-going',
  1190. action='store_true',
  1191. help="Don't stop on first error.")
  1192. bench_parser.add_argument(
  1193. '-i', '--isolate',
  1194. action='store_true',
  1195. help="Run each bench permutation in a separate process.")
  1196. bench_parser.add_argument(
  1197. '-b', '--by-suites',
  1198. action='store_true',
  1199. help="Step through benches by suite.")
  1200. bench_parser.add_argument(
  1201. '-B', '--by-cases',
  1202. action='store_true',
  1203. help="Step through benches by case.")
  1204. bench_parser.add_argument(
  1205. '--context',
  1206. type=lambda x: int(x, 0),
  1207. default=5,
  1208. help="Show this many lines of stdout on bench failure. "
  1209. "Defaults to 5.")
  1210. bench_parser.add_argument(
  1211. '--gdb',
  1212. action='store_true',
  1213. help="Drop into gdb on bench failure.")
  1214. bench_parser.add_argument(
  1215. '--gdb-case',
  1216. action='store_true',
  1217. help="Drop into gdb on bench failure but stop at the beginning "
  1218. "of the failing bench case.")
  1219. bench_parser.add_argument(
  1220. '--gdb-main',
  1221. action='store_true',
  1222. help="Drop into gdb on bench failure but stop at the beginning "
  1223. "of main.")
  1224. bench_parser.add_argument(
  1225. '--gdb-tool',
  1226. type=lambda x: x.split(),
  1227. default=GDB_TOOL,
  1228. help="Path to gdb tool to use. Defaults to %r." % GDB_TOOL)
  1229. bench_parser.add_argument(
  1230. '--exec',
  1231. type=lambda e: e.split(),
  1232. help="Run under another executable.")
  1233. bench_parser.add_argument(
  1234. '--valgrind',
  1235. action='store_true',
  1236. help="Run under Valgrind to find memory errors. Implicitly sets "
  1237. "--isolate.")
  1238. bench_parser.add_argument(
  1239. '--valgrind-tool',
  1240. type=lambda x: x.split(),
  1241. default=VALGRIND_TOOL,
  1242. help="Path to Valgrind tool to use. Defaults to %r." % VALGRIND_TOOL)
  1243. bench_parser.add_argument(
  1244. '-p', '--perf',
  1245. help="Run under Linux's perf to sample performance counters, writing "
  1246. "samples to this file.")
  1247. bench_parser.add_argument(
  1248. '--perf-freq',
  1249. help="perf sampling frequency. This is passed directly to the perf "
  1250. "script.")
  1251. bench_parser.add_argument(
  1252. '--perf-period',
  1253. help="perf sampling period. This is passed directly to the perf "
  1254. "script.")
  1255. bench_parser.add_argument(
  1256. '--perf-events',
  1257. help="perf events to record. This is passed directly to the perf "
  1258. "script.")
  1259. bench_parser.add_argument(
  1260. '--perf-script',
  1261. type=lambda x: x.split(),
  1262. default=PERF_SCRIPT,
  1263. help="Path to the perf script to use. Defaults to %r." % PERF_SCRIPT)
  1264. bench_parser.add_argument(
  1265. '--perf-tool',
  1266. type=lambda x: x.split(),
  1267. help="Path to the perf tool to use. This is passed directly to the "
  1268. "perf script")
  1269. # compilation flags
  1270. comp_parser = parser.add_argument_group('compilation options')
  1271. comp_parser.add_argument(
  1272. 'bench_paths',
  1273. nargs='*',
  1274. help="Description of *.toml files to compile. May be a directory "
  1275. "or a list of paths.")
  1276. comp_parser.add_argument(
  1277. '-c', '--compile',
  1278. action='store_true',
  1279. help="Compile a bench suite or source file.")
  1280. comp_parser.add_argument(
  1281. '-s', '--source',
  1282. help="Source file to compile, possibly injecting internal benches.")
  1283. comp_parser.add_argument(
  1284. '--include',
  1285. default=HEADER_PATH,
  1286. help="Inject this header file into every compiled bench file. "
  1287. "Defaults to %r." % HEADER_PATH)
  1288. comp_parser.add_argument(
  1289. '-o', '--output',
  1290. help="Output file.")
  1291. # runner/bench_paths overlap, so need to do some munging here
  1292. args = parser.parse_intermixed_args()
  1293. args.bench_paths = [' '.join(args.runner or [])] + args.bench_ids
  1294. args.runner = args.runner or [RUNNER_PATH]
  1295. sys.exit(main(**{k: v
  1296. for k, v in vars(args).items()
  1297. if v is not None}))