parallel-perf.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0
  3. #
  4. # Run a perf script command multiple times in parallel, using perf script
  5. # options --cpu and --time so that each job processes a different chunk
  6. # of the data.
  7. #
  8. # Copyright (c) 2024, Intel Corporation.
  9. import subprocess
  10. import argparse
  11. import pathlib
  12. import shlex
  13. import time
  14. import copy
  15. import sys
  16. import os
  17. import re
  18. glb_prog_name = "parallel-perf.py"
  19. glb_min_interval = 10.0
  20. glb_min_samples = 64
  21. class Verbosity():
  22. def __init__(self, quiet=False, verbose=False, debug=False):
  23. self.normal = True
  24. self.verbose = verbose
  25. self.debug = debug
  26. self.self_test = True
  27. if self.debug:
  28. self.verbose = True
  29. if self.verbose:
  30. quiet = False
  31. if quiet:
  32. self.normal = False
  33. # Manage work (Start/Wait/Kill), as represented by a subprocess.Popen command
  34. class Work():
  35. def __init__(self, cmd, pipe_to, output_dir="."):
  36. self.popen = None
  37. self.consumer = None
  38. self.cmd = cmd
  39. self.pipe_to = pipe_to
  40. self.output_dir = output_dir
  41. self.cmdout_name = f"{output_dir}/cmd.txt"
  42. self.stdout_name = f"{output_dir}/out.txt"
  43. self.stderr_name = f"{output_dir}/err.txt"
  44. def Command(self):
  45. sh_cmd = [ shlex.quote(x) for x in self.cmd ]
  46. return " ".join(self.cmd)
  47. def Stdout(self):
  48. return open(self.stdout_name, "w")
  49. def Stderr(self):
  50. return open(self.stderr_name, "w")
  51. def CreateOutputDir(self):
  52. pathlib.Path(self.output_dir).mkdir(parents=True, exist_ok=True)
  53. def Start(self):
  54. if self.popen:
  55. return
  56. self.CreateOutputDir()
  57. with open(self.cmdout_name, "w") as f:
  58. f.write(self.Command())
  59. f.write("\n")
  60. stdout = self.Stdout()
  61. stderr = self.Stderr()
  62. if self.pipe_to:
  63. self.popen = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=stderr)
  64. args = shlex.split(self.pipe_to)
  65. self.consumer = subprocess.Popen(args, stdin=self.popen.stdout, stdout=stdout, stderr=stderr)
  66. else:
  67. self.popen = subprocess.Popen(self.cmd, stdout=stdout, stderr=stderr)
  68. def RemoveEmptyErrFile(self):
  69. if os.path.exists(self.stderr_name):
  70. if os.path.getsize(self.stderr_name) == 0:
  71. os.unlink(self.stderr_name)
  72. def Errors(self):
  73. if os.path.exists(self.stderr_name):
  74. if os.path.getsize(self.stderr_name) != 0:
  75. return [ f"Non-empty error file {self.stderr_name}" ]
  76. return []
  77. def TidyUp(self):
  78. self.RemoveEmptyErrFile()
  79. def RawPollWait(self, p, wait):
  80. if wait:
  81. return p.wait()
  82. return p.poll()
  83. def Poll(self, wait=False):
  84. if not self.popen:
  85. return None
  86. result = self.RawPollWait(self.popen, wait)
  87. if self.consumer:
  88. res = result
  89. result = self.RawPollWait(self.consumer, wait)
  90. if result != None and res == None:
  91. self.popen.kill()
  92. result = None
  93. elif result == 0 and res != None and res != 0:
  94. result = res
  95. if result != None:
  96. self.TidyUp()
  97. return result
  98. def Wait(self):
  99. return self.Poll(wait=True)
  100. def Kill(self):
  101. if not self.popen:
  102. return
  103. self.popen.kill()
  104. if self.consumer:
  105. self.consumer.kill()
  106. def KillWork(worklist, verbosity):
  107. for w in worklist:
  108. w.Kill()
  109. for w in worklist:
  110. w.Wait()
  111. def NumberOfCPUs():
  112. return os.sysconf("SC_NPROCESSORS_ONLN")
  113. def NanoSecsToSecsStr(x):
  114. if x == None:
  115. return ""
  116. x = str(x)
  117. if len(x) < 10:
  118. x = "0" * (10 - len(x)) + x
  119. return x[:len(x) - 9] + "." + x[-9:]
  120. def InsertOptionAfter(cmd, option, after):
  121. try:
  122. pos = cmd.index(after)
  123. cmd.insert(pos + 1, option)
  124. except:
  125. cmd.append(option)
  126. def CreateWorkList(cmd, pipe_to, output_dir, cpus, time_ranges_by_cpu):
  127. max_len = len(str(cpus[-1]))
  128. cpu_dir_fmt = f"cpu-%.{max_len}u"
  129. worklist = []
  130. pos = 0
  131. for cpu in cpus:
  132. if cpu >= 0:
  133. cpu_dir = os.path.join(output_dir, cpu_dir_fmt % cpu)
  134. cpu_option = f"--cpu={cpu}"
  135. else:
  136. cpu_dir = output_dir
  137. cpu_option = None
  138. tr_dir_fmt = "time-range"
  139. if len(time_ranges_by_cpu) > 1:
  140. time_ranges = time_ranges_by_cpu[pos]
  141. tr_dir_fmt += f"-{pos}"
  142. pos += 1
  143. else:
  144. time_ranges = time_ranges_by_cpu[0]
  145. max_len = len(str(len(time_ranges)))
  146. tr_dir_fmt += f"-%.{max_len}u"
  147. i = 0
  148. for r in time_ranges:
  149. if r == [None, None]:
  150. time_option = None
  151. work_output_dir = cpu_dir
  152. else:
  153. time_option = "--time=" + NanoSecsToSecsStr(r[0]) + "," + NanoSecsToSecsStr(r[1])
  154. work_output_dir = os.path.join(cpu_dir, tr_dir_fmt % i)
  155. i += 1
  156. work_cmd = list(cmd)
  157. if time_option != None:
  158. InsertOptionAfter(work_cmd, time_option, "script")
  159. if cpu_option != None:
  160. InsertOptionAfter(work_cmd, cpu_option, "script")
  161. w = Work(work_cmd, pipe_to, work_output_dir)
  162. worklist.append(w)
  163. return worklist
  164. def DoRunWork(worklist, nr_jobs, verbosity):
  165. nr_to_do = len(worklist)
  166. not_started = list(worklist)
  167. running = []
  168. done = []
  169. chg = False
  170. while True:
  171. nr_done = len(done)
  172. if chg and verbosity.normal:
  173. nr_run = len(running)
  174. print(f"\rThere are {nr_to_do} jobs: {nr_done} completed, {nr_run} running", flush=True, end=" ")
  175. if verbosity.verbose:
  176. print()
  177. chg = False
  178. if nr_done == nr_to_do:
  179. break
  180. while len(running) < nr_jobs and len(not_started):
  181. w = not_started.pop(0)
  182. running.append(w)
  183. if verbosity.verbose:
  184. print("Starting:", w.Command())
  185. w.Start()
  186. chg = True
  187. if len(running):
  188. time.sleep(0.1)
  189. finished = []
  190. not_finished = []
  191. while len(running):
  192. w = running.pop(0)
  193. r = w.Poll()
  194. if r == None:
  195. not_finished.append(w)
  196. continue
  197. if r == 0:
  198. if verbosity.verbose:
  199. print("Finished:", w.Command())
  200. finished.append(w)
  201. chg = True
  202. continue
  203. if verbosity.normal and not verbosity.verbose:
  204. print()
  205. print("Job failed!\n return code:", r, "\n command: ", w.Command())
  206. if w.pipe_to:
  207. print(" piped to: ", w.pipe_to)
  208. print("Killing outstanding jobs")
  209. KillWork(not_finished, verbosity)
  210. KillWork(running, verbosity)
  211. return False
  212. running = not_finished
  213. done += finished
  214. errorlist = []
  215. for w in worklist:
  216. errorlist += w.Errors()
  217. if len(errorlist):
  218. print("Errors:")
  219. for e in errorlist:
  220. print(e)
  221. elif verbosity.normal:
  222. print("\r"," "*50, "\rAll jobs finished successfully", flush=True)
  223. return True
  224. def RunWork(worklist, nr_jobs=NumberOfCPUs(), verbosity=Verbosity()):
  225. try:
  226. return DoRunWork(worklist, nr_jobs, verbosity)
  227. except:
  228. for w in worklist:
  229. w.Kill()
  230. raise
  231. return True
  232. def ReadHeader(perf, file_name):
  233. return subprocess.Popen([perf, "script", "--header-only", "--input", file_name], stdout=subprocess.PIPE).stdout.read().decode("utf-8")
  234. def ParseHeader(hdr):
  235. result = {}
  236. lines = hdr.split("\n")
  237. for line in lines:
  238. if ":" in line and line[0] == "#":
  239. pos = line.index(":")
  240. name = line[1:pos-1].strip()
  241. value = line[pos+1:].strip()
  242. if name in result:
  243. orig_name = name
  244. nr = 2
  245. while True:
  246. name = f"{orig_name} {nr}"
  247. if name not in result:
  248. break
  249. nr += 1
  250. result[name] = value
  251. return result
  252. def HeaderField(hdr_dict, hdr_fld):
  253. if hdr_fld not in hdr_dict:
  254. raise Exception(f"'{hdr_fld}' missing from header information")
  255. return hdr_dict[hdr_fld]
  256. # Represent the position of an option within a command string
  257. # and provide the option value and/or remove the option
  258. class OptPos():
  259. def Init(self, opt_element=-1, value_element=-1, opt_pos=-1, value_pos=-1, error=None):
  260. self.opt_element = opt_element # list element that contains option
  261. self.value_element = value_element # list element that contains option value
  262. self.opt_pos = opt_pos # string position of option
  263. self.value_pos = value_pos # string position of value
  264. self.error = error # error message string
  265. def __init__(self, args, short_name, long_name, default=None):
  266. self.args = list(args)
  267. self.default = default
  268. n = 2 + len(long_name)
  269. m = len(short_name)
  270. pos = -1
  271. for opt in args:
  272. pos += 1
  273. if m and opt[:2] == f"-{short_name}":
  274. if len(opt) == 2:
  275. if pos + 1 < len(args):
  276. self.Init(pos, pos + 1, 0, 0)
  277. else:
  278. self.Init(error = f"-{short_name} option missing value")
  279. else:
  280. self.Init(pos, pos, 0, 2)
  281. return
  282. if opt[:n] == f"--{long_name}":
  283. if len(opt) == n:
  284. if pos + 1 < len(args):
  285. self.Init(pos, pos + 1, 0, 0)
  286. else:
  287. self.Init(error = f"--{long_name} option missing value")
  288. elif opt[n] == "=":
  289. self.Init(pos, pos, 0, n + 1)
  290. else:
  291. self.Init(error = f"--{long_name} option expected '='")
  292. return
  293. if m and opt[:1] == "-" and opt[:2] != "--" and short_name in opt:
  294. ipos = opt.index(short_name)
  295. if "-" in opt[1:]:
  296. hpos = opt[1:].index("-")
  297. if hpos < ipos:
  298. continue
  299. if ipos + 1 == len(opt):
  300. if pos + 1 < len(args):
  301. self.Init(pos, pos + 1, ipos, 0)
  302. else:
  303. self.Init(error = f"-{short_name} option missing value")
  304. else:
  305. self.Init(pos, pos, ipos, ipos + 1)
  306. return
  307. self.Init()
  308. def Value(self):
  309. if self.opt_element >= 0:
  310. if self.opt_element != self.value_element:
  311. return self.args[self.value_element]
  312. else:
  313. return self.args[self.value_element][self.value_pos:]
  314. return self.default
  315. def Remove(self, args):
  316. if self.opt_element == -1:
  317. return
  318. if self.opt_element != self.value_element:
  319. del args[self.value_element]
  320. if self.opt_pos:
  321. args[self.opt_element] = args[self.opt_element][:self.opt_pos]
  322. else:
  323. del args[self.opt_element]
  324. def DetermineInputFileName(cmd):
  325. p = OptPos(cmd, "i", "input", "perf.data")
  326. if p.error:
  327. raise Exception(f"perf command {p.error}")
  328. file_name = p.Value()
  329. if not os.path.exists(file_name):
  330. raise Exception(f"perf command input file '{file_name}' not found")
  331. return file_name
  332. def ReadOption(args, short_name, long_name, err_prefix, remove=False):
  333. p = OptPos(args, short_name, long_name)
  334. if p.error:
  335. raise Exception(f"{err_prefix}{p.error}")
  336. value = p.Value()
  337. if remove:
  338. p.Remove(args)
  339. return value
  340. def ExtractOption(args, short_name, long_name, err_prefix):
  341. return ReadOption(args, short_name, long_name, err_prefix, True)
  342. def ReadPerfOption(args, short_name, long_name):
  343. return ReadOption(args, short_name, long_name, "perf command ")
  344. def ExtractPerfOption(args, short_name, long_name):
  345. return ExtractOption(args, short_name, long_name, "perf command ")
  346. def PerfDoubleQuickCommands(cmd, file_name):
  347. cpu_str = ReadPerfOption(cmd, "C", "cpu")
  348. time_str = ReadPerfOption(cmd, "", "time")
  349. # Use double-quick sampling to determine trace data density
  350. times_cmd = ["perf", "script", "--ns", "--input", file_name, "--itrace=qqi"]
  351. if cpu_str != None and cpu_str != "":
  352. times_cmd.append(f"--cpu={cpu_str}")
  353. if time_str != None and time_str != "":
  354. times_cmd.append(f"--time={time_str}")
  355. cnts_cmd = list(times_cmd)
  356. cnts_cmd.append("-Fcpu")
  357. times_cmd.append("-Fcpu,time")
  358. return cnts_cmd, times_cmd
  359. class CPUTimeRange():
  360. def __init__(self, cpu):
  361. self.cpu = cpu
  362. self.sample_cnt = 0
  363. self.time_ranges = None
  364. self.interval = 0
  365. self.interval_remaining = 0
  366. self.remaining = 0
  367. self.tr_pos = 0
  368. def CalcTimeRangesByCPU(line, cpu, cpu_time_ranges, max_time):
  369. cpu_time_range = cpu_time_ranges[cpu]
  370. cpu_time_range.remaining -= 1
  371. cpu_time_range.interval_remaining -= 1
  372. if cpu_time_range.remaining == 0:
  373. cpu_time_range.time_ranges[cpu_time_range.tr_pos][1] = max_time
  374. return
  375. if cpu_time_range.interval_remaining == 0:
  376. time = TimeVal(line[1][:-1], 0)
  377. time_ranges = cpu_time_range.time_ranges
  378. time_ranges[cpu_time_range.tr_pos][1] = time - 1
  379. time_ranges.append([time, max_time])
  380. cpu_time_range.tr_pos += 1
  381. cpu_time_range.interval_remaining = cpu_time_range.interval
  382. def CountSamplesByCPU(line, cpu, cpu_time_ranges):
  383. try:
  384. cpu_time_ranges[cpu].sample_cnt += 1
  385. except:
  386. print("exception")
  387. print("cpu", cpu)
  388. print("len(cpu_time_ranges)", len(cpu_time_ranges))
  389. raise
  390. def ProcessCommandOutputLines(cmd, per_cpu, fn, *x):
  391. # Assume CPU number is at beginning of line and enclosed by []
  392. pat = re.compile(r"\s*\[[0-9]+\]")
  393. p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  394. while True:
  395. line = p.stdout.readline()
  396. if line:
  397. line = line.decode("utf-8")
  398. if pat.match(line):
  399. line = line.split()
  400. if per_cpu:
  401. # Assumes CPU number is enclosed by []
  402. cpu = int(line[0][1:-1])
  403. else:
  404. cpu = 0
  405. fn(line, cpu, *x)
  406. else:
  407. break
  408. p.wait()
  409. def IntersectTimeRanges(new_time_ranges, time_ranges):
  410. pos = 0
  411. new_pos = 0
  412. # Can assume len(time_ranges) != 0 and len(new_time_ranges) != 0
  413. # Note also, there *must* be at least one intersection.
  414. while pos < len(time_ranges) and new_pos < len(new_time_ranges):
  415. # new end < old start => no intersection, remove new
  416. if new_time_ranges[new_pos][1] < time_ranges[pos][0]:
  417. del new_time_ranges[new_pos]
  418. continue
  419. # new start > old end => no intersection, check next
  420. if new_time_ranges[new_pos][0] > time_ranges[pos][1]:
  421. pos += 1
  422. if pos < len(time_ranges):
  423. continue
  424. # no next, so remove remaining
  425. while new_pos < len(new_time_ranges):
  426. del new_time_ranges[new_pos]
  427. return
  428. # Found an intersection
  429. # new start < old start => adjust new start = old start
  430. if new_time_ranges[new_pos][0] < time_ranges[pos][0]:
  431. new_time_ranges[new_pos][0] = time_ranges[pos][0]
  432. # new end > old end => keep the overlap, insert the remainder
  433. if new_time_ranges[new_pos][1] > time_ranges[pos][1]:
  434. r = [ time_ranges[pos][1] + 1, new_time_ranges[new_pos][1] ]
  435. new_time_ranges[new_pos][1] = time_ranges[pos][1]
  436. new_pos += 1
  437. new_time_ranges.insert(new_pos, r)
  438. continue
  439. # new [start, end] is within old [start, end]
  440. new_pos += 1
  441. def SplitTimeRangesByTraceDataDensity(time_ranges, cpus, nr, cmd, file_name, per_cpu, min_size, min_interval, verbosity):
  442. if verbosity.normal:
  443. print("\rAnalyzing...", flush=True, end=" ")
  444. if verbosity.verbose:
  445. print()
  446. cnts_cmd, times_cmd = PerfDoubleQuickCommands(cmd, file_name)
  447. nr_cpus = cpus[-1] + 1 if per_cpu else 1
  448. if per_cpu:
  449. nr_cpus = cpus[-1] + 1
  450. cpu_time_ranges = [ CPUTimeRange(cpu) for cpu in range(nr_cpus) ]
  451. else:
  452. nr_cpus = 1
  453. cpu_time_ranges = [ CPUTimeRange(-1) ]
  454. if verbosity.debug:
  455. print("nr_cpus", nr_cpus)
  456. print("cnts_cmd", cnts_cmd)
  457. print("times_cmd", times_cmd)
  458. # Count the number of "double quick" samples per CPU
  459. ProcessCommandOutputLines(cnts_cmd, per_cpu, CountSamplesByCPU, cpu_time_ranges)
  460. tot = 0
  461. mx = 0
  462. for cpu_time_range in cpu_time_ranges:
  463. cnt = cpu_time_range.sample_cnt
  464. tot += cnt
  465. if cnt > mx:
  466. mx = cnt
  467. if verbosity.debug:
  468. print("cpu:", cpu_time_range.cpu, "sample_cnt", cnt)
  469. if min_size < 1:
  470. min_size = 1
  471. if mx < min_size:
  472. # Too little data to be worth splitting
  473. if verbosity.debug:
  474. print("Too little data to split by time")
  475. if nr == 0:
  476. nr = 1
  477. return [ SplitTimeRangesIntoN(time_ranges, nr, min_interval) ]
  478. if nr:
  479. divisor = nr
  480. min_size = 1
  481. else:
  482. divisor = NumberOfCPUs()
  483. interval = int(round(tot / divisor, 0))
  484. if interval < min_size:
  485. interval = min_size
  486. if verbosity.debug:
  487. print("divisor", divisor)
  488. print("min_size", min_size)
  489. print("interval", interval)
  490. min_time = time_ranges[0][0]
  491. max_time = time_ranges[-1][1]
  492. for cpu_time_range in cpu_time_ranges:
  493. cnt = cpu_time_range.sample_cnt
  494. if cnt == 0:
  495. cpu_time_range.time_ranges = copy.deepcopy(time_ranges)
  496. continue
  497. # Adjust target interval for CPU to give approximately equal interval sizes
  498. # Determine number of intervals, rounding to nearest integer
  499. n = int(round(cnt / interval, 0))
  500. if n < 1:
  501. n = 1
  502. # Determine interval size, rounding up
  503. d, m = divmod(cnt, n)
  504. if m:
  505. d += 1
  506. cpu_time_range.interval = d
  507. cpu_time_range.interval_remaining = d
  508. cpu_time_range.remaining = cnt
  509. # Init. time ranges for each CPU with the start time
  510. cpu_time_range.time_ranges = [ [min_time, max_time] ]
  511. # Set time ranges so that the same number of "double quick" samples
  512. # will fall into each time range.
  513. ProcessCommandOutputLines(times_cmd, per_cpu, CalcTimeRangesByCPU, cpu_time_ranges, max_time)
  514. for cpu_time_range in cpu_time_ranges:
  515. if cpu_time_range.sample_cnt:
  516. IntersectTimeRanges(cpu_time_range.time_ranges, time_ranges)
  517. return [cpu_time_ranges[cpu].time_ranges for cpu in cpus]
  518. def SplitSingleTimeRangeIntoN(time_range, n):
  519. if n <= 1:
  520. return [time_range]
  521. start = time_range[0]
  522. end = time_range[1]
  523. duration = int((end - start + 1) / n)
  524. if duration < 1:
  525. return [time_range]
  526. time_ranges = []
  527. for i in range(n):
  528. time_ranges.append([start, start + duration - 1])
  529. start += duration
  530. time_ranges[-1][1] = end
  531. return time_ranges
  532. def TimeRangeDuration(r):
  533. return r[1] - r[0] + 1
  534. def TotalDuration(time_ranges):
  535. duration = 0
  536. for r in time_ranges:
  537. duration += TimeRangeDuration(r)
  538. return duration
  539. def SplitTimeRangesByInterval(time_ranges, interval):
  540. new_ranges = []
  541. for r in time_ranges:
  542. duration = TimeRangeDuration(r)
  543. n = duration / interval
  544. n = int(round(n, 0))
  545. new_ranges += SplitSingleTimeRangeIntoN(r, n)
  546. return new_ranges
  547. def SplitTimeRangesIntoN(time_ranges, n, min_interval):
  548. if n <= len(time_ranges):
  549. return time_ranges
  550. duration = TotalDuration(time_ranges)
  551. interval = duration / n
  552. if interval < min_interval:
  553. interval = min_interval
  554. return SplitTimeRangesByInterval(time_ranges, interval)
  555. def RecombineTimeRanges(tr):
  556. new_tr = copy.deepcopy(tr)
  557. n = len(new_tr)
  558. i = 1
  559. while i < len(new_tr):
  560. # if prev end + 1 == cur start, combine them
  561. if new_tr[i - 1][1] + 1 == new_tr[i][0]:
  562. new_tr[i][0] = new_tr[i - 1][0]
  563. del new_tr[i - 1]
  564. else:
  565. i += 1
  566. return new_tr
  567. def OpenTimeRangeEnds(time_ranges, min_time, max_time):
  568. if time_ranges[0][0] <= min_time:
  569. time_ranges[0][0] = None
  570. if time_ranges[-1][1] >= max_time:
  571. time_ranges[-1][1] = None
  572. def BadTimeStr(time_str):
  573. raise Exception(f"perf command bad time option: '{time_str}'\nCheck also 'time of first sample' and 'time of last sample' in perf script --header-only")
  574. def ValidateTimeRanges(time_ranges, time_str):
  575. n = len(time_ranges)
  576. for i in range(n):
  577. start = time_ranges[i][0]
  578. end = time_ranges[i][1]
  579. if i != 0 and start <= time_ranges[i - 1][1]:
  580. BadTimeStr(time_str)
  581. if start > end:
  582. BadTimeStr(time_str)
  583. def TimeVal(s, dflt):
  584. s = s.strip()
  585. if s == "":
  586. return dflt
  587. a = s.split(".")
  588. if len(a) > 2:
  589. raise Exception(f"Bad time value'{s}'")
  590. x = int(a[0])
  591. if x < 0:
  592. raise Exception("Negative time not allowed")
  593. x *= 1000000000
  594. if len(a) > 1:
  595. x += int((a[1] + "000000000")[:9])
  596. return x
  597. def BadCPUStr(cpu_str):
  598. raise Exception(f"perf command bad cpu option: '{cpu_str}'\nCheck also 'nrcpus avail' in perf script --header-only")
  599. def ParseTimeStr(time_str, min_time, max_time):
  600. if time_str == None or time_str == "":
  601. return [[min_time, max_time]]
  602. time_ranges = []
  603. for r in time_str.split():
  604. a = r.split(",")
  605. if len(a) != 2:
  606. BadTimeStr(time_str)
  607. try:
  608. start = TimeVal(a[0], min_time)
  609. end = TimeVal(a[1], max_time)
  610. except:
  611. BadTimeStr(time_str)
  612. time_ranges.append([start, end])
  613. ValidateTimeRanges(time_ranges, time_str)
  614. return time_ranges
  615. def ParseCPUStr(cpu_str, nr_cpus):
  616. if cpu_str == None or cpu_str == "":
  617. return [-1]
  618. cpus = []
  619. for r in cpu_str.split(","):
  620. a = r.split("-")
  621. if len(a) < 1 or len(a) > 2:
  622. BadCPUStr(cpu_str)
  623. try:
  624. start = int(a[0].strip())
  625. if len(a) > 1:
  626. end = int(a[1].strip())
  627. else:
  628. end = start
  629. except:
  630. BadCPUStr(cpu_str)
  631. if start < 0 or end < 0 or end < start or end >= nr_cpus:
  632. BadCPUStr(cpu_str)
  633. cpus.extend(range(start, end + 1))
  634. cpus = list(set(cpus)) # Remove duplicates
  635. cpus.sort()
  636. return cpus
  637. class ParallelPerf():
  638. def __init__(self, a):
  639. for arg_name in vars(a):
  640. setattr(self, arg_name, getattr(a, arg_name))
  641. self.orig_nr = self.nr
  642. self.orig_cmd = list(self.cmd)
  643. self.perf = self.cmd[0]
  644. if os.path.exists(self.output_dir):
  645. raise Exception(f"Output '{self.output_dir}' already exists")
  646. if self.jobs < 0 or self.nr < 0 or self.interval < 0:
  647. raise Exception("Bad options (negative values): try -h option for help")
  648. if self.nr != 0 and self.interval != 0:
  649. raise Exception("Cannot specify number of time subdivisions and time interval")
  650. if self.jobs == 0:
  651. self.jobs = NumberOfCPUs()
  652. if self.nr == 0 and self.interval == 0:
  653. if self.per_cpu:
  654. self.nr = 1
  655. else:
  656. self.nr = self.jobs
  657. def Init(self):
  658. if self.verbosity.debug:
  659. print("cmd", self.cmd)
  660. self.file_name = DetermineInputFileName(self.cmd)
  661. self.hdr = ReadHeader(self.perf, self.file_name)
  662. self.hdr_dict = ParseHeader(self.hdr)
  663. self.cmd_line = HeaderField(self.hdr_dict, "cmdline")
  664. def ExtractTimeInfo(self):
  665. self.min_time = TimeVal(HeaderField(self.hdr_dict, "time of first sample"), 0)
  666. self.max_time = TimeVal(HeaderField(self.hdr_dict, "time of last sample"), 0)
  667. self.time_str = ExtractPerfOption(self.cmd, "", "time")
  668. self.time_ranges = ParseTimeStr(self.time_str, self.min_time, self.max_time)
  669. if self.verbosity.debug:
  670. print("time_ranges", self.time_ranges)
  671. def ExtractCPUInfo(self):
  672. if self.per_cpu:
  673. nr_cpus = int(HeaderField(self.hdr_dict, "nrcpus avail"))
  674. self.cpu_str = ExtractPerfOption(self.cmd, "C", "cpu")
  675. if self.cpu_str == None or self.cpu_str == "":
  676. self.cpus = [ x for x in range(nr_cpus) ]
  677. else:
  678. self.cpus = ParseCPUStr(self.cpu_str, nr_cpus)
  679. else:
  680. self.cpu_str = None
  681. self.cpus = [-1]
  682. if self.verbosity.debug:
  683. print("cpus", self.cpus)
  684. def IsIntelPT(self):
  685. return self.cmd_line.find("intel_pt") >= 0
  686. def SplitTimeRanges(self):
  687. if self.IsIntelPT() and self.interval == 0:
  688. self.split_time_ranges_for_each_cpu = \
  689. SplitTimeRangesByTraceDataDensity(self.time_ranges, self.cpus, self.orig_nr,
  690. self.orig_cmd, self.file_name, self.per_cpu,
  691. self.min_size, self.min_interval, self.verbosity)
  692. elif self.nr:
  693. self.split_time_ranges_for_each_cpu = [ SplitTimeRangesIntoN(self.time_ranges, self.nr, self.min_interval) ]
  694. else:
  695. self.split_time_ranges_for_each_cpu = [ SplitTimeRangesByInterval(self.time_ranges, self.interval) ]
  696. def CheckTimeRanges(self):
  697. for tr in self.split_time_ranges_for_each_cpu:
  698. # Re-combined time ranges should be the same
  699. new_tr = RecombineTimeRanges(tr)
  700. if new_tr != self.time_ranges:
  701. if self.verbosity.debug:
  702. print("tr", tr)
  703. print("new_tr", new_tr)
  704. raise Exception("Self test failed!")
  705. def OpenTimeRangeEnds(self):
  706. for time_ranges in self.split_time_ranges_for_each_cpu:
  707. OpenTimeRangeEnds(time_ranges, self.min_time, self.max_time)
  708. def CreateWorkList(self):
  709. self.worklist = CreateWorkList(self.cmd, self.pipe_to, self.output_dir, self.cpus, self.split_time_ranges_for_each_cpu)
  710. def PerfDataRecordedPerCPU(self):
  711. if "--per-thread" in self.cmd_line.split():
  712. return False
  713. return True
  714. def DefaultToPerCPU(self):
  715. # --no-per-cpu option takes precedence
  716. if self.no_per_cpu:
  717. return False
  718. if not self.PerfDataRecordedPerCPU():
  719. return False
  720. # Default to per-cpu for Intel PT data that was recorded per-cpu,
  721. # because decoding can be done for each CPU separately.
  722. if self.IsIntelPT():
  723. return True
  724. return False
  725. def Config(self):
  726. self.Init()
  727. self.ExtractTimeInfo()
  728. if not self.per_cpu:
  729. self.per_cpu = self.DefaultToPerCPU()
  730. if self.verbosity.debug:
  731. print("per_cpu", self.per_cpu)
  732. self.ExtractCPUInfo()
  733. self.SplitTimeRanges()
  734. if self.verbosity.self_test:
  735. self.CheckTimeRanges()
  736. # Prefer open-ended time range to starting / ending with min_time / max_time resp.
  737. self.OpenTimeRangeEnds()
  738. self.CreateWorkList()
  739. def Run(self):
  740. if self.dry_run:
  741. print(len(self.worklist),"jobs:")
  742. for w in self.worklist:
  743. print(w.Command())
  744. return True
  745. result = RunWork(self.worklist, self.jobs, verbosity=self.verbosity)
  746. if self.verbosity.verbose:
  747. print(glb_prog_name, "done")
  748. return result
  749. def RunParallelPerf(a):
  750. pp = ParallelPerf(a)
  751. pp.Config()
  752. return pp.Run()
  753. def Main(args):
  754. ap = argparse.ArgumentParser(
  755. prog=glb_prog_name, formatter_class = argparse.RawDescriptionHelpFormatter,
  756. description =
  757. """
  758. Run a perf script command multiple times in parallel, using perf script options
  759. --cpu and --time so that each job processes a different chunk of the data.
  760. """,
  761. epilog =
  762. """
  763. Follow the options by '--' and then the perf script command e.g.
  764. $ perf record -a -- sleep 10
  765. $ parallel-perf.py --nr=4 -- perf script --ns
  766. All jobs finished successfully
  767. $ tree parallel-perf-output/
  768. parallel-perf-output/
  769. ├── time-range-0
  770. │   ├── cmd.txt
  771. │   └── out.txt
  772. ├── time-range-1
  773. │   ├── cmd.txt
  774. │   └── out.txt
  775. ├── time-range-2
  776. │   ├── cmd.txt
  777. │   └── out.txt
  778. └── time-range-3
  779. ├── cmd.txt
  780. └── out.txt
  781. $ find parallel-perf-output -name cmd.txt | sort | xargs grep -H .
  782. parallel-perf-output/time-range-0/cmd.txt:perf script --time=,9466.504461499 --ns
  783. parallel-perf-output/time-range-1/cmd.txt:perf script --time=9466.504461500,9469.005396999 --ns
  784. parallel-perf-output/time-range-2/cmd.txt:perf script --time=9469.005397000,9471.506332499 --ns
  785. parallel-perf-output/time-range-3/cmd.txt:perf script --time=9471.506332500, --ns
  786. Any perf script command can be used, including the use of perf script options
  787. --dlfilter and --script, so that the benefit of running parallel jobs
  788. naturally extends to them also.
  789. If option --pipe-to is used, standard output is first piped through that
  790. command. Beware, if the command fails (e.g. grep with no matches), it will be
  791. considered a fatal error.
  792. Final standard output is redirected to files named out.txt in separate
  793. subdirectories under the output directory. Similarly, standard error is
  794. written to files named err.txt. In addition, files named cmd.txt contain the
  795. corresponding perf script command. After processing, err.txt files are removed
  796. if they are empty.
  797. If any job exits with a non-zero exit code, then all jobs are killed and no
  798. more are started. A message is printed if any job results in a non-empty
  799. err.txt file.
  800. There is a separate output subdirectory for each time range. If the --per-cpu
  801. option is used, these are further grouped under cpu-n subdirectories, e.g.
  802. $ parallel-perf.py --per-cpu --nr=2 -- perf script --ns --cpu=0,1
  803. All jobs finished successfully
  804. $ tree parallel-perf-output
  805. parallel-perf-output/
  806. ├── cpu-0
  807. │   ├── time-range-0
  808. │   │   ├── cmd.txt
  809. │   │   └── out.txt
  810. │   └── time-range-1
  811. │   ├── cmd.txt
  812. │   └── out.txt
  813. └── cpu-1
  814. ├── time-range-0
  815. │   ├── cmd.txt
  816. │   └── out.txt
  817. └── time-range-1
  818. ├── cmd.txt
  819. └── out.txt
  820. $ find parallel-perf-output -name cmd.txt | sort | xargs grep -H .
  821. parallel-perf-output/cpu-0/time-range-0/cmd.txt:perf script --cpu=0 --time=,9469.005396999 --ns
  822. parallel-perf-output/cpu-0/time-range-1/cmd.txt:perf script --cpu=0 --time=9469.005397000, --ns
  823. parallel-perf-output/cpu-1/time-range-0/cmd.txt:perf script --cpu=1 --time=,9469.005396999 --ns
  824. parallel-perf-output/cpu-1/time-range-1/cmd.txt:perf script --cpu=1 --time=9469.005397000, --ns
  825. Subdivisions of time range, and cpus if the --per-cpu option is used, are
  826. expressed by the --time and --cpu perf script options respectively. If the
  827. supplied perf script command has a --time option, then that time range is
  828. subdivided, otherwise the time range given by 'time of first sample' to
  829. 'time of last sample' is used (refer perf script --header-only). Similarly, the
  830. supplied perf script command may provide a --cpu option, and only those CPUs
  831. will be processed.
  832. To prevent time intervals becoming too small, the --min-interval option can
  833. be used.
  834. Note there is special handling for processing Intel PT traces. If an interval is
  835. not specified and the perf record command contained the intel_pt event, then the
  836. time range will be subdivided in order to produce subdivisions that contain
  837. approximately the same amount of trace data. That is accomplished by counting
  838. double-quick (--itrace=qqi) samples, and choosing time ranges that encompass
  839. approximately the same number of samples. In that case, time ranges may not be
  840. the same for each CPU processed. For Intel PT, --per-cpu is the default, but
  841. that can be overridden by --no-per-cpu. Note, for Intel PT, double-quick
  842. decoding produces 1 sample for each PSB synchronization packet, which in turn
  843. come after a certain number of bytes output, determined by psb_period (refer
  844. perf Intel PT documentation). The minimum number of double-quick samples that
  845. will define a time range can be set by the --min_size option, which defaults to
  846. 64.
  847. """)
  848. ap.add_argument("-o", "--output-dir", default="parallel-perf-output", help="output directory (default 'parallel-perf-output')")
  849. ap.add_argument("-j", "--jobs", type=int, default=0, help="maximum number of jobs to run in parallel at one time (default is the number of CPUs)")
  850. ap.add_argument("-n", "--nr", type=int, default=0, help="number of time subdivisions (default is the number of jobs)")
  851. ap.add_argument("-i", "--interval", type=float, default=0, help="subdivide the time range using this time interval (in seconds e.g. 0.1 for a tenth of a second)")
  852. ap.add_argument("-c", "--per-cpu", action="store_true", help="process data for each CPU in parallel")
  853. ap.add_argument("-m", "--min-interval", type=float, default=glb_min_interval, help=f"minimum interval (default {glb_min_interval} seconds)")
  854. ap.add_argument("-p", "--pipe-to", help="command to pipe output to (optional)")
  855. ap.add_argument("-N", "--no-per-cpu", action="store_true", help="do not process data for each CPU in parallel")
  856. ap.add_argument("-b", "--min_size", type=int, default=glb_min_samples, help="minimum data size (for Intel PT in PSBs)")
  857. ap.add_argument("-D", "--dry-run", action="store_true", help="do not run any jobs, just show the perf script commands")
  858. ap.add_argument("-q", "--quiet", action="store_true", help="do not print any messages except errors")
  859. ap.add_argument("-v", "--verbose", action="store_true", help="print more messages")
  860. ap.add_argument("-d", "--debug", action="store_true", help="print debugging messages")
  861. cmd_line = list(args)
  862. try:
  863. split_pos = cmd_line.index("--")
  864. cmd = cmd_line[split_pos + 1:]
  865. args = cmd_line[:split_pos]
  866. except:
  867. cmd = None
  868. args = cmd_line
  869. a = ap.parse_args(args=args[1:])
  870. a.cmd = cmd
  871. a.verbosity = Verbosity(a.quiet, a.verbose, a.debug)
  872. try:
  873. if a.cmd == None:
  874. if len(args) <= 1:
  875. ap.print_help()
  876. return True
  877. raise Exception("Command line must contain '--' before perf command")
  878. return RunParallelPerf(a)
  879. except Exception as e:
  880. print("Fatal error: ", str(e))
  881. if a.debug:
  882. raise
  883. return False
  884. if __name__ == "__main__":
  885. if not Main(sys.argv):
  886. sys.exit(1)