bench.py 51 KB

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