task-analyzer.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. # task-analyzer.py - comprehensive perf tasks analysis
  2. # SPDX-License-Identifier: GPL-2.0
  3. # Copyright (c) 2022, Hagen Paul Pfeifer <hagen@jauu.net>
  4. # Licensed under the terms of the GNU GPL License version 2
  5. #
  6. # Usage:
  7. #
  8. # perf record -e sched:sched_switch -a -- sleep 10
  9. # perf script report task-analyzer
  10. #
  11. from __future__ import print_function
  12. import sys
  13. import os
  14. import string
  15. import argparse
  16. import decimal
  17. sys.path.append(
  18. os.environ["PERF_EXEC_PATH"] + "/scripts/python/Perf-Trace-Util/lib/Perf/Trace"
  19. )
  20. from perf_trace_context import *
  21. from Core import *
  22. # Definition of possible ASCII color codes
  23. _COLORS = {
  24. "grey": "\033[90m",
  25. "red": "\033[91m",
  26. "green": "\033[92m",
  27. "yellow": "\033[93m",
  28. "blue": "\033[94m",
  29. "violet": "\033[95m",
  30. "reset": "\033[0m",
  31. }
  32. # Columns will have a static size to align everything properly
  33. # Support of 116 days of active update with nano precision
  34. LEN_SWITCHED_IN = len("9999999.999999999") # 17
  35. LEN_SWITCHED_OUT = len("9999999.999999999") # 17
  36. LEN_CPU = len("000")
  37. LEN_PID = len("maxvalue") # 8
  38. LEN_TID = len("maxvalue") # 8
  39. LEN_COMM = len("max-comms-length") # 16
  40. LEN_RUNTIME = len("999999.999") # 10
  41. # Support of 3.45 hours of timespans
  42. LEN_OUT_IN = len("99999999999.999") # 15
  43. LEN_OUT_OUT = len("99999999999.999") # 15
  44. LEN_IN_IN = len("99999999999.999") # 15
  45. LEN_IN_OUT = len("99999999999.999") # 15
  46. # py2/py3 compatibility layer, see PEP469
  47. try:
  48. dict.iteritems
  49. except AttributeError:
  50. # py3
  51. def itervalues(d):
  52. return iter(d.values())
  53. def iteritems(d):
  54. return iter(d.items())
  55. else:
  56. # py2
  57. def itervalues(d):
  58. return d.itervalues()
  59. def iteritems(d):
  60. return d.iteritems()
  61. def _check_color():
  62. global _COLORS
  63. """user enforced no-color or if stdout is no tty we disable colors"""
  64. if sys.stdout.isatty() and args.stdio_color != "never":
  65. return
  66. _COLORS = {
  67. "grey": "",
  68. "red": "",
  69. "green": "",
  70. "yellow": "",
  71. "blue": "",
  72. "violet": "",
  73. "reset": "",
  74. }
  75. def _parse_args():
  76. global args
  77. parser = argparse.ArgumentParser(description="Analyze tasks behavior")
  78. parser.add_argument(
  79. "--time-limit",
  80. default=[],
  81. help=
  82. "print tasks only in time[s] window e.g"
  83. " --time-limit 123.111:789.222(print all between 123.111 and 789.222)"
  84. " --time-limit 123: (print all from 123)"
  85. " --time-limit :456 (print all until incl. 456)",
  86. )
  87. parser.add_argument(
  88. "--summary", action="store_true", help="print addtional runtime information"
  89. )
  90. parser.add_argument(
  91. "--summary-only", action="store_true", help="print only summary without traces"
  92. )
  93. parser.add_argument(
  94. "--summary-extended",
  95. action="store_true",
  96. help="print the summary with additional information of max inter task times"
  97. " relative to the prev task",
  98. )
  99. parser.add_argument(
  100. "--ns", action="store_true", help="show timestamps in nanoseconds"
  101. )
  102. parser.add_argument(
  103. "--ms", action="store_true", help="show timestamps in milliseconds"
  104. )
  105. parser.add_argument(
  106. "--extended-times",
  107. action="store_true",
  108. help="Show the elapsed times between schedule in/schedule out"
  109. " of this task and the schedule in/schedule out of previous occurrence"
  110. " of the same task",
  111. )
  112. parser.add_argument(
  113. "--filter-tasks",
  114. default=[],
  115. help="filter out unneeded tasks by tid, pid or processname."
  116. " E.g --filter-task 1337,/sbin/init ",
  117. )
  118. parser.add_argument(
  119. "--limit-to-tasks",
  120. default=[],
  121. help="limit output to selected task by tid, pid, processname."
  122. " E.g --limit-to-tasks 1337,/sbin/init",
  123. )
  124. parser.add_argument(
  125. "--highlight-tasks",
  126. default="",
  127. help="colorize special tasks by their pid/tid/comm."
  128. " E.g. --highlight-tasks 1:red,mutt:yellow"
  129. " Colors available: red,grey,yellow,blue,violet,green",
  130. )
  131. parser.add_argument(
  132. "--rename-comms-by-tids",
  133. default="",
  134. help="rename task names by using tid (<tid>:<newname>,<tid>:<newname>)"
  135. " This option is handy for inexpressive processnames like python interpreted"
  136. " process. E.g --rename 1337:my-python-app",
  137. )
  138. parser.add_argument(
  139. "--stdio-color",
  140. default="auto",
  141. choices=["always", "never", "auto"],
  142. help="always, never or auto, allowing configuring color output"
  143. " via the command line",
  144. )
  145. parser.add_argument(
  146. "--csv",
  147. default="",
  148. help="Write trace to file selected by user. Options, like --ns or --extended"
  149. "-times are used.",
  150. )
  151. parser.add_argument(
  152. "--csv-summary",
  153. default="",
  154. help="Write summary to file selected by user. Options, like --ns or"
  155. " --summary-extended are used.",
  156. )
  157. args = parser.parse_args()
  158. args.tid_renames = dict()
  159. _argument_filter_sanity_check()
  160. _argument_prepare_check()
  161. def time_uniter(unit):
  162. picker = {
  163. "s": 1,
  164. "ms": 1e3,
  165. "us": 1e6,
  166. "ns": 1e9,
  167. }
  168. return picker[unit]
  169. def _init_db():
  170. global db
  171. db = dict()
  172. db["running"] = dict()
  173. db["cpu"] = dict()
  174. db["tid"] = dict()
  175. db["global"] = []
  176. if args.summary or args.summary_extended or args.summary_only:
  177. db["task_info"] = dict()
  178. db["runtime_info"] = dict()
  179. # min values for summary depending on the header
  180. db["task_info"]["pid"] = len("PID")
  181. db["task_info"]["tid"] = len("TID")
  182. db["task_info"]["comm"] = len("Comm")
  183. db["runtime_info"]["runs"] = len("Runs")
  184. db["runtime_info"]["acc"] = len("Accumulated")
  185. db["runtime_info"]["max"] = len("Max")
  186. db["runtime_info"]["max_at"] = len("Max At")
  187. db["runtime_info"]["min"] = len("Min")
  188. db["runtime_info"]["mean"] = len("Mean")
  189. db["runtime_info"]["median"] = len("Median")
  190. if args.summary_extended:
  191. db["inter_times"] = dict()
  192. db["inter_times"]["out_in"] = len("Out-In")
  193. db["inter_times"]["inter_at"] = len("At")
  194. db["inter_times"]["out_out"] = len("Out-Out")
  195. db["inter_times"]["in_in"] = len("In-In")
  196. db["inter_times"]["in_out"] = len("In-Out")
  197. def _median(numbers):
  198. """phython3 hat statistics module - we have nothing"""
  199. n = len(numbers)
  200. index = n // 2
  201. if n % 2:
  202. return sorted(numbers)[index]
  203. return sum(sorted(numbers)[index - 1 : index + 1]) / 2
  204. def _mean(numbers):
  205. return sum(numbers) / len(numbers)
  206. class Timespans(object):
  207. """
  208. The elapsed time between two occurrences of the same task is being tracked with the
  209. help of this class. There are 4 of those Timespans Out-Out, In-Out, Out-In and
  210. In-In.
  211. The first half of the name signals the first time point of the
  212. first task. The second half of the name represents the second
  213. timepoint of the second task.
  214. """
  215. def __init__(self):
  216. self._last_start = None
  217. self._last_finish = None
  218. self.out_out = -1
  219. self.in_out = -1
  220. self.out_in = -1
  221. self.in_in = -1
  222. if args.summary_extended:
  223. self._time_in = -1
  224. self.max_out_in = -1
  225. self.max_at = -1
  226. self.max_in_out = -1
  227. self.max_in_in = -1
  228. self.max_out_out = -1
  229. def feed(self, task):
  230. """
  231. Called for every recorded trace event to find process pair and calculate the
  232. task timespans. Chronological ordering, feed does not do reordering
  233. """
  234. if not self._last_finish:
  235. self._last_start = task.time_in(time_unit)
  236. self._last_finish = task.time_out(time_unit)
  237. return
  238. self._time_in = task.time_in()
  239. time_in = task.time_in(time_unit)
  240. time_out = task.time_out(time_unit)
  241. self.in_in = time_in - self._last_start
  242. self.out_in = time_in - self._last_finish
  243. self.in_out = time_out - self._last_start
  244. self.out_out = time_out - self._last_finish
  245. if args.summary_extended:
  246. self._update_max_entries()
  247. self._last_finish = task.time_out(time_unit)
  248. self._last_start = task.time_in(time_unit)
  249. def _update_max_entries(self):
  250. if self.in_in > self.max_in_in:
  251. self.max_in_in = self.in_in
  252. if self.out_out > self.max_out_out:
  253. self.max_out_out = self.out_out
  254. if self.in_out > self.max_in_out:
  255. self.max_in_out = self.in_out
  256. if self.out_in > self.max_out_in:
  257. self.max_out_in = self.out_in
  258. self.max_at = self._time_in
  259. class Summary(object):
  260. """
  261. Primary instance for calculating the summary output. Processes the whole trace to
  262. find and memorize relevant data such as mean, max et cetera. This instance handles
  263. dynamic alignment aspects for summary output.
  264. """
  265. def __init__(self):
  266. self._body = []
  267. class AlignmentHelper:
  268. """
  269. Used to calculated the alignment for the output of the summary.
  270. """
  271. def __init__(self, pid, tid, comm, runs, acc, mean,
  272. median, min, max, max_at):
  273. self.pid = pid
  274. self.tid = tid
  275. self.comm = comm
  276. self.runs = runs
  277. self.acc = acc
  278. self.mean = mean
  279. self.median = median
  280. self.min = min
  281. self.max = max
  282. self.max_at = max_at
  283. if args.summary_extended:
  284. self.out_in = None
  285. self.inter_at = None
  286. self.out_out = None
  287. self.in_in = None
  288. self.in_out = None
  289. def _print_header(self):
  290. '''
  291. Output is trimmed in _format_stats thus additional adjustment in the header
  292. is needed, depending on the choice of timeunit. The adjustment corresponds
  293. to the amount of column titles being adjusted in _column_titles.
  294. '''
  295. decimal_precision = 6 if not args.ns else 9
  296. fmt = " {{:^{}}}".format(sum(db["task_info"].values()))
  297. fmt += " {{:^{}}}".format(
  298. sum(db["runtime_info"].values()) - 2 * decimal_precision
  299. )
  300. _header = ("Task Information", "Runtime Information")
  301. if args.summary_extended:
  302. fmt += " {{:^{}}}".format(
  303. sum(db["inter_times"].values()) - 4 * decimal_precision
  304. )
  305. _header += ("Max Inter Task Times",)
  306. fd_sum.write(fmt.format(*_header) + "\n")
  307. def _column_titles(self):
  308. """
  309. Cells are being processed and displayed in different way so an alignment adjust
  310. is implemented depeding on the choice of the timeunit. The positions of the max
  311. values are being displayed in grey. Thus in their format two additional {},
  312. are placed for color set and reset.
  313. """
  314. separator, fix_csv_align = _prepare_fmt_sep()
  315. decimal_precision, time_precision = _prepare_fmt_precision()
  316. fmt = "{{:>{}}}".format(db["task_info"]["pid"] * fix_csv_align)
  317. fmt += "{}{{:>{}}}".format(separator, db["task_info"]["tid"] * fix_csv_align)
  318. fmt += "{}{{:>{}}}".format(separator, db["task_info"]["comm"] * fix_csv_align)
  319. fmt += "{}{{:>{}}}".format(separator, db["runtime_info"]["runs"] * fix_csv_align)
  320. fmt += "{}{{:>{}}}".format(separator, db["runtime_info"]["acc"] * fix_csv_align)
  321. fmt += "{}{{:>{}}}".format(separator, db["runtime_info"]["mean"] * fix_csv_align)
  322. fmt += "{}{{:>{}}}".format(
  323. separator, db["runtime_info"]["median"] * fix_csv_align
  324. )
  325. fmt += "{}{{:>{}}}".format(
  326. separator, (db["runtime_info"]["min"] - decimal_precision) * fix_csv_align
  327. )
  328. fmt += "{}{{:>{}}}".format(
  329. separator, (db["runtime_info"]["max"] - decimal_precision) * fix_csv_align
  330. )
  331. fmt += "{}{{}}{{:>{}}}{{}}".format(
  332. separator, (db["runtime_info"]["max_at"] - time_precision) * fix_csv_align
  333. )
  334. column_titles = ("PID", "TID", "Comm")
  335. column_titles += ("Runs", "Accumulated", "Mean", "Median", "Min", "Max")
  336. column_titles += (_COLORS["grey"], "Max At", _COLORS["reset"])
  337. if args.summary_extended:
  338. fmt += "{}{{:>{}}}".format(
  339. separator,
  340. (db["inter_times"]["out_in"] - decimal_precision) * fix_csv_align
  341. )
  342. fmt += "{}{{}}{{:>{}}}{{}}".format(
  343. separator,
  344. (db["inter_times"]["inter_at"] - time_precision) * fix_csv_align
  345. )
  346. fmt += "{}{{:>{}}}".format(
  347. separator,
  348. (db["inter_times"]["out_out"] - decimal_precision) * fix_csv_align
  349. )
  350. fmt += "{}{{:>{}}}".format(
  351. separator,
  352. (db["inter_times"]["in_in"] - decimal_precision) * fix_csv_align
  353. )
  354. fmt += "{}{{:>{}}}".format(
  355. separator,
  356. (db["inter_times"]["in_out"] - decimal_precision) * fix_csv_align
  357. )
  358. column_titles += ("Out-In", _COLORS["grey"], "Max At", _COLORS["reset"],
  359. "Out-Out", "In-In", "In-Out")
  360. fd_sum.write(fmt.format(*column_titles) + "\n")
  361. def _task_stats(self):
  362. """calculates the stats of every task and constructs the printable summary"""
  363. for tid in sorted(db["tid"]):
  364. color_one_sample = _COLORS["grey"]
  365. color_reset = _COLORS["reset"]
  366. no_executed = 0
  367. runtimes = []
  368. time_in = []
  369. timespans = Timespans()
  370. for task in db["tid"][tid]:
  371. pid = task.pid
  372. comm = task.comm
  373. no_executed += 1
  374. runtimes.append(task.runtime(time_unit))
  375. time_in.append(task.time_in())
  376. timespans.feed(task)
  377. if len(runtimes) > 1:
  378. color_one_sample = ""
  379. color_reset = ""
  380. time_max = max(runtimes)
  381. time_min = min(runtimes)
  382. max_at = time_in[runtimes.index(max(runtimes))]
  383. # The size of the decimal after sum,mean and median varies, thus we cut
  384. # the decimal number, by rounding it. It has no impact on the output,
  385. # because we have a precision of the decimal points at the output.
  386. time_sum = round(sum(runtimes), 3)
  387. time_mean = round(_mean(runtimes), 3)
  388. time_median = round(_median(runtimes), 3)
  389. align_helper = self.AlignmentHelper(pid, tid, comm, no_executed, time_sum,
  390. time_mean, time_median, time_min, time_max, max_at)
  391. self._body.append([pid, tid, comm, no_executed, time_sum, color_one_sample,
  392. time_mean, time_median, time_min, time_max,
  393. _COLORS["grey"], max_at, _COLORS["reset"], color_reset])
  394. if args.summary_extended:
  395. self._body[-1].extend([timespans.max_out_in,
  396. _COLORS["grey"], timespans.max_at,
  397. _COLORS["reset"], timespans.max_out_out,
  398. timespans.max_in_in,
  399. timespans.max_in_out])
  400. align_helper.out_in = timespans.max_out_in
  401. align_helper.inter_at = timespans.max_at
  402. align_helper.out_out = timespans.max_out_out
  403. align_helper.in_in = timespans.max_in_in
  404. align_helper.in_out = timespans.max_in_out
  405. self._calc_alignments_summary(align_helper)
  406. def _format_stats(self):
  407. separator, fix_csv_align = _prepare_fmt_sep()
  408. decimal_precision, time_precision = _prepare_fmt_precision()
  409. len_pid = db["task_info"]["pid"] * fix_csv_align
  410. len_tid = db["task_info"]["tid"] * fix_csv_align
  411. len_comm = db["task_info"]["comm"] * fix_csv_align
  412. len_runs = db["runtime_info"]["runs"] * fix_csv_align
  413. len_acc = db["runtime_info"]["acc"] * fix_csv_align
  414. len_mean = db["runtime_info"]["mean"] * fix_csv_align
  415. len_median = db["runtime_info"]["median"] * fix_csv_align
  416. len_min = (db["runtime_info"]["min"] - decimal_precision) * fix_csv_align
  417. len_max = (db["runtime_info"]["max"] - decimal_precision) * fix_csv_align
  418. len_max_at = (db["runtime_info"]["max_at"] - time_precision) * fix_csv_align
  419. if args.summary_extended:
  420. len_out_in = (
  421. db["inter_times"]["out_in"] - decimal_precision
  422. ) * fix_csv_align
  423. len_inter_at = (
  424. db["inter_times"]["inter_at"] - time_precision
  425. ) * fix_csv_align
  426. len_out_out = (
  427. db["inter_times"]["out_out"] - decimal_precision
  428. ) * fix_csv_align
  429. len_in_in = (db["inter_times"]["in_in"] - decimal_precision) * fix_csv_align
  430. len_in_out = (
  431. db["inter_times"]["in_out"] - decimal_precision
  432. ) * fix_csv_align
  433. fmt = "{{:{}d}}".format(len_pid)
  434. fmt += "{}{{:{}d}}".format(separator, len_tid)
  435. fmt += "{}{{:>{}}}".format(separator, len_comm)
  436. fmt += "{}{{:{}d}}".format(separator, len_runs)
  437. fmt += "{}{{:{}.{}f}}".format(separator, len_acc, time_precision)
  438. fmt += "{}{{}}{{:{}.{}f}}".format(separator, len_mean, time_precision)
  439. fmt += "{}{{:{}.{}f}}".format(separator, len_median, time_precision)
  440. fmt += "{}{{:{}.{}f}}".format(separator, len_min, time_precision)
  441. fmt += "{}{{:{}.{}f}}".format(separator, len_max, time_precision)
  442. fmt += "{}{{}}{{:{}.{}f}}{{}}{{}}".format(
  443. separator, len_max_at, decimal_precision
  444. )
  445. if args.summary_extended:
  446. fmt += "{}{{:{}.{}f}}".format(separator, len_out_in, time_precision)
  447. fmt += "{}{{}}{{:{}.{}f}}{{}}".format(
  448. separator, len_inter_at, decimal_precision
  449. )
  450. fmt += "{}{{:{}.{}f}}".format(separator, len_out_out, time_precision)
  451. fmt += "{}{{:{}.{}f}}".format(separator, len_in_in, time_precision)
  452. fmt += "{}{{:{}.{}f}}".format(separator, len_in_out, time_precision)
  453. return fmt
  454. def _calc_alignments_summary(self, align_helper):
  455. # Length is being cut in 3 groups so that further addition is easier to handle.
  456. # The length of every argument from the alignment helper is being checked if it
  457. # is longer than the longest until now. In that case the length is being saved.
  458. for key in db["task_info"]:
  459. if len(str(getattr(align_helper, key))) > db["task_info"][key]:
  460. db["task_info"][key] = len(str(getattr(align_helper, key)))
  461. for key in db["runtime_info"]:
  462. if len(str(getattr(align_helper, key))) > db["runtime_info"][key]:
  463. db["runtime_info"][key] = len(str(getattr(align_helper, key)))
  464. if args.summary_extended:
  465. for key in db["inter_times"]:
  466. if len(str(getattr(align_helper, key))) > db["inter_times"][key]:
  467. db["inter_times"][key] = len(str(getattr(align_helper, key)))
  468. def print(self):
  469. self._task_stats()
  470. fmt = self._format_stats()
  471. if not args.csv_summary:
  472. print("\nSummary")
  473. self._print_header()
  474. self._column_titles()
  475. for i in range(len(self._body)):
  476. fd_sum.write(fmt.format(*tuple(self._body[i])) + "\n")
  477. class Task(object):
  478. """ The class is used to handle the information of a given task."""
  479. def __init__(self, id, tid, cpu, comm):
  480. self.id = id
  481. self.tid = tid
  482. self.cpu = cpu
  483. self.comm = comm
  484. self.pid = None
  485. self._time_in = None
  486. self._time_out = None
  487. def schedule_in_at(self, time):
  488. """set the time where the task was scheduled in"""
  489. self._time_in = time
  490. def schedule_out_at(self, time):
  491. """set the time where the task was scheduled out"""
  492. self._time_out = time
  493. def time_out(self, unit="s"):
  494. """return time where a given task was scheduled out"""
  495. factor = time_uniter(unit)
  496. return self._time_out * decimal.Decimal(factor)
  497. def time_in(self, unit="s"):
  498. """return time where a given task was scheduled in"""
  499. factor = time_uniter(unit)
  500. return self._time_in * decimal.Decimal(factor)
  501. def runtime(self, unit="us"):
  502. factor = time_uniter(unit)
  503. return (self._time_out - self._time_in) * decimal.Decimal(factor)
  504. def update_pid(self, pid):
  505. self.pid = pid
  506. def _task_id(pid, cpu):
  507. """returns a "unique-enough" identifier, please do not change"""
  508. return "{}-{}".format(pid, cpu)
  509. def _filter_non_printable(unfiltered):
  510. """comm names may contain loony chars like '\x00000'"""
  511. filtered = ""
  512. for char in unfiltered:
  513. if char not in string.printable:
  514. continue
  515. filtered += char
  516. return filtered
  517. def _fmt_header():
  518. separator, fix_csv_align = _prepare_fmt_sep()
  519. fmt = "{{:>{}}}".format(LEN_SWITCHED_IN*fix_csv_align)
  520. fmt += "{}{{:>{}}}".format(separator, LEN_SWITCHED_OUT*fix_csv_align)
  521. fmt += "{}{{:>{}}}".format(separator, LEN_CPU*fix_csv_align)
  522. fmt += "{}{{:>{}}}".format(separator, LEN_PID*fix_csv_align)
  523. fmt += "{}{{:>{}}}".format(separator, LEN_TID*fix_csv_align)
  524. fmt += "{}{{:>{}}}".format(separator, LEN_COMM*fix_csv_align)
  525. fmt += "{}{{:>{}}}".format(separator, LEN_RUNTIME*fix_csv_align)
  526. fmt += "{}{{:>{}}}".format(separator, LEN_OUT_IN*fix_csv_align)
  527. if args.extended_times:
  528. fmt += "{}{{:>{}}}".format(separator, LEN_OUT_OUT*fix_csv_align)
  529. fmt += "{}{{:>{}}}".format(separator, LEN_IN_IN*fix_csv_align)
  530. fmt += "{}{{:>{}}}".format(separator, LEN_IN_OUT*fix_csv_align)
  531. return fmt
  532. def _fmt_body():
  533. separator, fix_csv_align = _prepare_fmt_sep()
  534. decimal_precision, time_precision = _prepare_fmt_precision()
  535. fmt = "{{}}{{:{}.{}f}}".format(LEN_SWITCHED_IN*fix_csv_align, decimal_precision)
  536. fmt += "{}{{:{}.{}f}}".format(
  537. separator, LEN_SWITCHED_OUT*fix_csv_align, decimal_precision
  538. )
  539. fmt += "{}{{:{}d}}".format(separator, LEN_CPU*fix_csv_align)
  540. fmt += "{}{{:{}d}}".format(separator, LEN_PID*fix_csv_align)
  541. fmt += "{}{{}}{{:{}d}}{{}}".format(separator, LEN_TID*fix_csv_align)
  542. fmt += "{}{{}}{{:>{}}}".format(separator, LEN_COMM*fix_csv_align)
  543. fmt += "{}{{:{}.{}f}}".format(separator, LEN_RUNTIME*fix_csv_align, time_precision)
  544. if args.extended_times:
  545. fmt += "{}{{:{}.{}f}}".format(separator, LEN_OUT_IN*fix_csv_align, time_precision)
  546. fmt += "{}{{:{}.{}f}}".format(separator, LEN_OUT_OUT*fix_csv_align, time_precision)
  547. fmt += "{}{{:{}.{}f}}".format(separator, LEN_IN_IN*fix_csv_align, time_precision)
  548. fmt += "{}{{:{}.{}f}}{{}}".format(
  549. separator, LEN_IN_OUT*fix_csv_align, time_precision
  550. )
  551. else:
  552. fmt += "{}{{:{}.{}f}}{{}}".format(
  553. separator, LEN_OUT_IN*fix_csv_align, time_precision
  554. )
  555. return fmt
  556. def _print_header():
  557. fmt = _fmt_header()
  558. header = ("Switched-In", "Switched-Out", "CPU", "PID", "TID", "Comm", "Runtime",
  559. "Time Out-In")
  560. if args.extended_times:
  561. header += ("Time Out-Out", "Time In-In", "Time In-Out")
  562. fd_task.write(fmt.format(*header) + "\n")
  563. def _print_task_finish(task):
  564. """calculating every entry of a row and printing it immediately"""
  565. c_row_set = ""
  566. c_row_reset = ""
  567. out_in = -1
  568. out_out = -1
  569. in_in = -1
  570. in_out = -1
  571. fmt = _fmt_body()
  572. # depending on user provided highlight option we change the color
  573. # for particular tasks
  574. if str(task.tid) in args.highlight_tasks_map:
  575. c_row_set = _COLORS[args.highlight_tasks_map[str(task.tid)]]
  576. c_row_reset = _COLORS["reset"]
  577. if task.comm in args.highlight_tasks_map:
  578. c_row_set = _COLORS[args.highlight_tasks_map[task.comm]]
  579. c_row_reset = _COLORS["reset"]
  580. # grey-out entries if PID == TID, they
  581. # are identical, no threaded model so the
  582. # thread id (tid) do not matter
  583. c_tid_set = ""
  584. c_tid_reset = ""
  585. if task.pid == task.tid:
  586. c_tid_set = _COLORS["grey"]
  587. c_tid_reset = _COLORS["reset"]
  588. if task.tid in db["tid"]:
  589. # get last task of tid
  590. last_tid_task = db["tid"][task.tid][-1]
  591. # feed the timespan calculate, last in tid db
  592. # and second the current one
  593. timespan_gap_tid = Timespans()
  594. timespan_gap_tid.feed(last_tid_task)
  595. timespan_gap_tid.feed(task)
  596. out_in = timespan_gap_tid.out_in
  597. out_out = timespan_gap_tid.out_out
  598. in_in = timespan_gap_tid.in_in
  599. in_out = timespan_gap_tid.in_out
  600. if args.extended_times:
  601. line_out = fmt.format(c_row_set, task.time_in(), task.time_out(), task.cpu,
  602. task.pid, c_tid_set, task.tid, c_tid_reset, c_row_set, task.comm,
  603. task.runtime(time_unit), out_in, out_out, in_in, in_out,
  604. c_row_reset) + "\n"
  605. else:
  606. line_out = fmt.format(c_row_set, task.time_in(), task.time_out(), task.cpu,
  607. task.pid, c_tid_set, task.tid, c_tid_reset, c_row_set, task.comm,
  608. task.runtime(time_unit), out_in, c_row_reset) + "\n"
  609. try:
  610. fd_task.write(line_out)
  611. except(IOError):
  612. # don't mangle the output if user SIGINT this script
  613. sys.exit()
  614. def _record_cleanup(_list):
  615. """
  616. no need to store more then one element if --summarize
  617. is not enabled
  618. """
  619. if not args.summary and len(_list) > 1:
  620. _list = _list[len(_list) - 1 :]
  621. def _record_by_tid(task):
  622. tid = task.tid
  623. if tid not in db["tid"]:
  624. db["tid"][tid] = []
  625. db["tid"][tid].append(task)
  626. _record_cleanup(db["tid"][tid])
  627. def _record_by_cpu(task):
  628. cpu = task.cpu
  629. if cpu not in db["cpu"]:
  630. db["cpu"][cpu] = []
  631. db["cpu"][cpu].append(task)
  632. _record_cleanup(db["cpu"][cpu])
  633. def _record_global(task):
  634. """record all executed task, ordered by finish chronological"""
  635. db["global"].append(task)
  636. _record_cleanup(db["global"])
  637. def _handle_task_finish(tid, cpu, time, perf_sample_dict):
  638. if tid == 0:
  639. return
  640. _id = _task_id(tid, cpu)
  641. if _id not in db["running"]:
  642. # may happen, if we missed the switch to
  643. # event. Seen in combination with --exclude-perf
  644. # where the start is filtered out, but not the
  645. # switched in. Probably a bug in exclude-perf
  646. # option.
  647. return
  648. task = db["running"][_id]
  649. task.schedule_out_at(time)
  650. # record tid, during schedule in the tid
  651. # is not available, update now
  652. pid = int(perf_sample_dict["sample"]["pid"])
  653. task.update_pid(pid)
  654. del db["running"][_id]
  655. # print only tasks which are not being filtered and no print of trace
  656. # for summary only, but record every task.
  657. if not _limit_filtered(tid, pid, task.comm) and not args.summary_only:
  658. _print_task_finish(task)
  659. _record_by_tid(task)
  660. _record_by_cpu(task)
  661. _record_global(task)
  662. def _handle_task_start(tid, cpu, comm, time):
  663. if tid == 0:
  664. return
  665. if tid in args.tid_renames:
  666. comm = args.tid_renames[tid]
  667. _id = _task_id(tid, cpu)
  668. if _id in db["running"]:
  669. # handle corner cases where already running tasks
  670. # are switched-to again - saw this via --exclude-perf
  671. # recorded traces. We simple ignore this "second start"
  672. # event.
  673. return
  674. assert _id not in db["running"]
  675. task = Task(_id, tid, cpu, comm)
  676. task.schedule_in_at(time)
  677. db["running"][_id] = task
  678. def _time_to_internal(time_ns):
  679. """
  680. To prevent float rounding errors we use Decimal internally
  681. """
  682. return decimal.Decimal(time_ns) / decimal.Decimal(1e9)
  683. def _limit_filtered(tid, pid, comm):
  684. if args.filter_tasks:
  685. if str(tid) in args.filter_tasks or comm in args.filter_tasks:
  686. return True
  687. else:
  688. return False
  689. if args.limit_to_tasks:
  690. if str(tid) in args.limit_to_tasks or comm in args.limit_to_tasks:
  691. return False
  692. else:
  693. return True
  694. def _argument_filter_sanity_check():
  695. if args.limit_to_tasks and args.filter_tasks:
  696. sys.exit("Error: Filter and Limit at the same time active.")
  697. if args.extended_times and args.summary_only:
  698. sys.exit("Error: Summary only and extended times active.")
  699. if args.time_limit and ":" not in args.time_limit:
  700. sys.exit(
  701. "Error: No bound set for time limit. Please set bound by ':' e.g :123."
  702. )
  703. if args.time_limit and (args.summary or args.summary_only or args.summary_extended):
  704. sys.exit("Error: Cannot set time limit and print summary")
  705. if args.csv_summary:
  706. args.summary = True
  707. if args.csv == args.csv_summary:
  708. sys.exit("Error: Chosen files for csv and csv summary are the same")
  709. if args.csv and (args.summary_extended or args.summary) and not args.csv_summary:
  710. sys.exit("Error: No file chosen to write summary to. Choose with --csv-summary "
  711. "<file>")
  712. if args.csv and args.summary_only:
  713. sys.exit("Error: --csv chosen and --summary-only. Standard task would not be"
  714. "written to csv file.")
  715. def _argument_prepare_check():
  716. global time_unit, fd_task, fd_sum
  717. if args.filter_tasks:
  718. args.filter_tasks = args.filter_tasks.split(",")
  719. if args.limit_to_tasks:
  720. args.limit_to_tasks = args.limit_to_tasks.split(",")
  721. if args.time_limit:
  722. args.time_limit = args.time_limit.split(":")
  723. for rename_tuple in args.rename_comms_by_tids.split(","):
  724. tid_name = rename_tuple.split(":")
  725. if len(tid_name) != 2:
  726. continue
  727. args.tid_renames[int(tid_name[0])] = tid_name[1]
  728. args.highlight_tasks_map = dict()
  729. for highlight_tasks_tuple in args.highlight_tasks.split(","):
  730. tasks_color_map = highlight_tasks_tuple.split(":")
  731. # default highlight color to red if no color set by user
  732. if len(tasks_color_map) == 1:
  733. tasks_color_map.append("red")
  734. if args.highlight_tasks and tasks_color_map[1].lower() not in _COLORS:
  735. sys.exit(
  736. "Error: Color not defined, please choose from grey,red,green,yellow,blue,"
  737. "violet"
  738. )
  739. if len(tasks_color_map) != 2:
  740. continue
  741. args.highlight_tasks_map[tasks_color_map[0]] = tasks_color_map[1]
  742. time_unit = "us"
  743. if args.ns:
  744. time_unit = "ns"
  745. elif args.ms:
  746. time_unit = "ms"
  747. fd_task = sys.stdout
  748. if args.csv:
  749. args.stdio_color = "never"
  750. fd_task = open(args.csv, "w")
  751. print("generating csv at",args.csv,)
  752. fd_sum = sys.stdout
  753. if args.csv_summary:
  754. args.stdio_color = "never"
  755. fd_sum = open(args.csv_summary, "w")
  756. print("generating csv summary at",args.csv_summary)
  757. if not args.csv:
  758. args.summary_only = True
  759. def _is_within_timelimit(time):
  760. """
  761. Check if a time limit was given by parameter, if so ignore the rest. If not,
  762. process the recorded trace in its entirety.
  763. """
  764. if not args.time_limit:
  765. return True
  766. lower_time_limit = args.time_limit[0]
  767. upper_time_limit = args.time_limit[1]
  768. # check for upper limit
  769. if upper_time_limit == "":
  770. if time >= decimal.Decimal(lower_time_limit):
  771. return True
  772. # check for lower limit
  773. if lower_time_limit == "":
  774. if time <= decimal.Decimal(upper_time_limit):
  775. return True
  776. # quit if time exceeds upper limit. Good for big datasets
  777. else:
  778. quit()
  779. if lower_time_limit != "" and upper_time_limit != "":
  780. if (time >= decimal.Decimal(lower_time_limit) and
  781. time <= decimal.Decimal(upper_time_limit)):
  782. return True
  783. # quit if time exceeds upper limit. Good for big datasets
  784. elif time > decimal.Decimal(upper_time_limit):
  785. quit()
  786. def _prepare_fmt_precision():
  787. decimal_precision = 6
  788. time_precision = 3
  789. if args.ns:
  790. decimal_precision = 9
  791. time_precision = 0
  792. return decimal_precision, time_precision
  793. def _prepare_fmt_sep():
  794. separator = " "
  795. fix_csv_align = 1
  796. if args.csv or args.csv_summary:
  797. separator = ";"
  798. fix_csv_align = 0
  799. return separator, fix_csv_align
  800. def trace_unhandled(event_name, context, event_fields_dict, perf_sample_dict):
  801. pass
  802. def trace_begin():
  803. _parse_args()
  804. _check_color()
  805. _init_db()
  806. if not args.summary_only:
  807. _print_header()
  808. def trace_end():
  809. if args.summary or args.summary_extended or args.summary_only:
  810. Summary().print()
  811. def sched__sched_switch(event_name, context, common_cpu, common_secs, common_nsecs,
  812. common_pid, common_comm, common_callchain, prev_comm,
  813. prev_pid, prev_prio, prev_state, next_comm, next_pid,
  814. next_prio, perf_sample_dict):
  815. # ignore common_secs & common_nsecs cause we need
  816. # high res timestamp anyway, using the raw value is
  817. # faster
  818. time = _time_to_internal(perf_sample_dict["sample"]["time"])
  819. if not _is_within_timelimit(time):
  820. # user specific --time-limit a:b set
  821. return
  822. next_comm = _filter_non_printable(next_comm)
  823. _handle_task_finish(prev_pid, common_cpu, time, perf_sample_dict)
  824. _handle_task_start(next_pid, common_cpu, next_comm, time)