starpu_trace_state_stats.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. #!/usr/bin/env python
  2. # StarPU --- Runtime system for heterogeneous multicore architectures.
  3. #
  4. # Copyright (C) 2016-2020 Université de Bordeaux, CNRS (LaBRI UMR 5800), Inria
  5. #
  6. # StarPU is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU Lesser General Public License as published by
  8. # the Free Software Foundation; either version 2.1 of the License, or (at
  9. # your option) any later version.
  10. #
  11. # StarPU is distributed in the hope that it will be useful, but
  12. # WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  14. #
  15. # See the GNU Lesser General Public License in COPYING.LGPL for more details.
  16. #
  17. ##
  18. # This script parses the generated trace.rec file and reports statistics about
  19. # the number of different events/tasks and their durations. The report is
  20. # similar to the starpu_paje_state_stats.in script, except that this one
  21. # doesn't need R and pj_dump (from the pajeng repository), and it is also much
  22. # faster.
  23. ##
  24. import getopt
  25. import os
  26. import sys
  27. class Event():
  28. def __init__(self, type, name, category, start_time):
  29. self._type = type
  30. self._name = name
  31. self._category = category
  32. self._start_time = start_time
  33. class EventStats():
  34. def __init__(self, name, duration_time, category, count = 1):
  35. self._name = name
  36. self._duration_time = duration_time
  37. self._category = category
  38. self._count = count
  39. def aggregate(self, duration_time):
  40. self._duration_time += duration_time
  41. self._count += 1
  42. def show(self):
  43. if not self._name == None and not self._category == None:
  44. print("\"" + self._name + "\"," + str(self._count) + ",\"" + self._category + "\"," + str(round(self._duration_time, 6)))
  45. class Worker():
  46. def __init__(self, id):
  47. self._id = id
  48. self._events = []
  49. self._stats = []
  50. self._stack = []
  51. self._current_state = None
  52. def get_event_stats(self, name):
  53. for stat in self._stats:
  54. if stat._name == name:
  55. return stat
  56. return None
  57. def add_event(self, type, name, category, start_time):
  58. self._events.append(Event(type, name, category, start_time))
  59. def add_event_to_stats(self, curr_event):
  60. if curr_event._type == "PushState":
  61. self._stack.append(curr_event)
  62. return # Will look later to find a PopState event.
  63. elif curr_event._type == "PopState":
  64. if len(self._stack) == 0:
  65. sys.exit("ERROR: The trace is most likely corrupted "
  66. "because a PopState event has been found without "
  67. "a PushState!")
  68. next_event = curr_event
  69. curr_event = self._stack.pop()
  70. elif curr_event._type == "SetState":
  71. if self._current_state == None:
  72. # First SetState event found
  73. self._current_state = curr_event
  74. return
  75. saved_state = curr_event
  76. next_event = curr_event
  77. curr_event = self._current_state
  78. self._current_state = saved_state
  79. else:
  80. sys.exit("ERROR: Invalid event type!")
  81. # Compute duration with the next event.
  82. a = curr_event._start_time
  83. b = next_event._start_time
  84. # Add the event to the list of stats.
  85. for i in range(len(self._stats)):
  86. if self._stats[i]._name == curr_event._name:
  87. self._stats[i].aggregate(b - a)
  88. return
  89. self._stats.append(EventStats(curr_event._name, b - a,
  90. curr_event._category))
  91. def calc_stats(self, start_profiling_times, stop_profiling_times):
  92. num_events = len(self._events)
  93. use_start_stop = len(start_profiling_times) != 0
  94. for i in range(0, num_events):
  95. event = self._events[i]
  96. if i > 0 and self._events[i-1]._name == "Deinitializing":
  97. # Drop all events after the Deinitializing event is found
  98. # because they do not make sense.
  99. break
  100. if not use_start_stop:
  101. self.add_event_to_stats(event)
  102. continue
  103. # Check if the event is inbetween start/stop profiling events
  104. for t in range(len(start_profiling_times)):
  105. if (event._start_time > start_profiling_times[t] and
  106. event._start_time < stop_profiling_times[t]):
  107. self.add_event_to_stats(event)
  108. break
  109. if not use_start_stop:
  110. return
  111. # Special case for SetState events which need a next one for computing
  112. # the duration.
  113. curr_event = self._events[-1]
  114. if curr_event._type == "SetState":
  115. for i in range(len(start_profiling_times)):
  116. if (curr_event._start_time > start_profiling_times[i] and
  117. curr_event._start_time < stop_profiling_times[i]):
  118. curr_event = Event(curr_event._type, curr_event._name,
  119. curr_event._category,
  120. stop_profiling_times[i])
  121. self.add_event_to_stats(curr_event)
  122. def read_blocks(input_file):
  123. empty_lines = 0
  124. first_line = 1
  125. blocks = []
  126. for line in open(input_file):
  127. if first_line:
  128. blocks.append([])
  129. blocks[-1].append(line)
  130. first_line = 0
  131. # Check for empty lines
  132. if not line or line[0] == '\n':
  133. # If 1st one: new block
  134. if empty_lines == 0:
  135. blocks.append([])
  136. empty_lines += 1
  137. else:
  138. # Non empty line: add line in current(last) block
  139. empty_lines = 0
  140. blocks[-1].append(line)
  141. return blocks
  142. def read_field(field, index):
  143. return field[index+1:-1]
  144. def insert_worker_event(workers, prog_events, block):
  145. worker_id = -1
  146. name = None
  147. start_time = 0.0
  148. category = None
  149. for line in block:
  150. key = line[:2]
  151. value = read_field(line, 2)
  152. if key == "E:": # EventType
  153. event_type = value
  154. elif key == "C:": # Category
  155. category = value
  156. elif key == "W:": # WorkerId
  157. worker_id = int(value)
  158. elif key == "N:": # Name
  159. name = value
  160. elif key == "S:": # StartTime
  161. start_time = float(value)
  162. # Program events don't belong to workers, they are globals.
  163. if category == "Program":
  164. prog_events.append(Event(event_type, name, category, start_time))
  165. return
  166. for worker in workers:
  167. if worker._id == worker_id:
  168. worker.add_event(event_type, name, category, start_time)
  169. return
  170. worker = Worker(worker_id)
  171. worker.add_event(event_type, name, category, start_time)
  172. workers.append(worker)
  173. def calc_times(stats):
  174. tr = 0.0 # Runtime
  175. tt = 0.0 # Task
  176. ti = 0.0 # Idle
  177. ts = 0.0 # Scheduling
  178. for stat in stats:
  179. if stat._category == None:
  180. continue
  181. if stat._category == "Runtime":
  182. if stat._name == "Scheduling":
  183. # Scheduling time is part of runtime but we want to have
  184. # it separately.
  185. ts += stat._duration_time
  186. else:
  187. tr += stat._duration_time
  188. elif stat._category == "Task":
  189. tt += stat._duration_time
  190. elif stat._category == "Other":
  191. ti += stat._duration_time
  192. else:
  193. print("WARNING: Unknown category '" + stat._category + "'!")
  194. return ti, tr, tt, ts
  195. def save_times(ti, tr, tt, ts):
  196. f = open("times.csv", "w+")
  197. f.write("\"Time\",\"Duration\"\n")
  198. f.write("\"Runtime\"," + str(tr) + "\n")
  199. f.write("\"Task\"," + str(tt) + "\n")
  200. f.write("\"Idle\"," + str(ti) + "\n")
  201. f.write("\"Scheduling\"," + str(ts) + "\n")
  202. f.close()
  203. def calc_et(tt_1, tt_p):
  204. """ Compute the task efficiency (et). This measures the exploitation of
  205. data locality. """
  206. return tt_1 / tt_p
  207. def calc_es(tt_p, ts_p):
  208. """ Compute the scheduling efficiency (es). This measures time spent in
  209. the runtime scheduler. """
  210. return tt_p / (tt_p + ts_p)
  211. def calc_er(tt_p, tr_p, ts_p):
  212. """ Compute the runtime efficiency (er). This measures how the runtime
  213. overhead affects performance."""
  214. return (tt_p + ts_p) / (tt_p + tr_p + ts_p)
  215. def calc_ep(tt_p, tr_p, ti_p, ts_p):
  216. """ Compute the pipeline efficiency (et). This measures how much
  217. concurrency is available and how well it's exploited. """
  218. return (tt_p + tr_p + ts_p) / (tt_p + tr_p + ti_p + ts_p)
  219. def calc_e(et, er, ep, es):
  220. """ Compute the parallel efficiency. """
  221. return et * er * ep * es
  222. def save_efficiencies(e, ep, er, et, es):
  223. f = open("efficiencies.csv", "w+")
  224. f.write("\"Efficiency\",\"Value\"\n")
  225. f.write("\"Parallel\"," + str(e) + "\n")
  226. f.write("\"Task\"," + str(et) + "\n")
  227. f.write("\"Runtime\"," + str(er) + "\n")
  228. f.write("\"Scheduling\"," + str(es) + "\n")
  229. f.write("\"Pipeline\"," + str(ep) + "\n")
  230. f.close()
  231. def usage():
  232. print("USAGE:")
  233. print("starpu_trace_state_stats.py [ -te -s=<time> ] <trace.rec>")
  234. print("")
  235. print("OPTIONS:")
  236. print(" -t or --time Compute and dump times to times.csv")
  237. print("")
  238. print(" -e or --efficiency Compute and dump efficiencies to efficiencies.csv")
  239. print("")
  240. print(" -s or --seq_task_time Used to compute task efficiency between sequential and parallel times")
  241. print(" (if not set, task efficiency will be 1.0)")
  242. print("")
  243. print("EXAMPLES:")
  244. print("# Compute event statistics and report them to stdout:")
  245. print("python starpu_trace_state_stats.py trace.rec")
  246. print("")
  247. print("# Compute event stats, times and efficiencies:")
  248. print("python starpu_trace_state_stats.py -te trace.rec")
  249. print("")
  250. print("# Compute correct task efficiency with the sequential task time:")
  251. print("python starpu_trace_state_stats.py -s=60093.950614 trace.rec")
  252. def main():
  253. try:
  254. opts, args = getopt.getopt(sys.argv[1:], "hets:",
  255. ["help", "time", "efficiency", "seq_task_time="])
  256. except getopt.GetoptError as err:
  257. usage()
  258. sys.exit(1)
  259. dump_time = False
  260. dump_efficiency = False
  261. tt_1 = 0.0
  262. for o, a in opts:
  263. if o in ("-h", "--help"):
  264. usage()
  265. sys.exit()
  266. elif o in ("-t", "--time"):
  267. dump_time = True
  268. elif o in ("-e", "--efficiency"):
  269. dump_efficiency = True
  270. elif o in ("-s", "--seq_task_time"):
  271. tt_1 = float(a)
  272. if len(args) < 1:
  273. usage()
  274. sys.exit()
  275. recfile = args[0]
  276. if not os.path.isfile(recfile):
  277. sys.exit("File does not exist!")
  278. # Declare a list for all workers.
  279. workers = []
  280. # Declare a list for program events
  281. prog_events = []
  282. # Read the recutils file format per blocks.
  283. blocks = read_blocks(recfile)
  284. for block in blocks:
  285. if not len(block) == 0:
  286. first_line = block[0]
  287. if first_line[:2] == "E:":
  288. insert_worker_event(workers, prog_events, block)
  289. # Find allowed range times between start/stop profiling events.
  290. start_profiling_times = []
  291. stop_profiling_times = []
  292. for prog_event in prog_events:
  293. if prog_event._name == "start_profiling":
  294. start_profiling_times.append(prog_event._start_time)
  295. if prog_event._name == "stop_profiling":
  296. stop_profiling_times.append(prog_event._start_time)
  297. if len(start_profiling_times) != len(stop_profiling_times):
  298. sys.exit("Mismatch number of start/stop profiling events!")
  299. # Compute worker statistics.
  300. stats = []
  301. for worker in workers:
  302. worker.calc_stats(start_profiling_times, stop_profiling_times)
  303. for stat in worker._stats:
  304. found = False
  305. for s in stats:
  306. if stat._name == s._name:
  307. found = True
  308. break
  309. if not found == True:
  310. stats.append(EventStats(stat._name, 0.0, stat._category, 0))
  311. # Compute global statistics for all workers.
  312. for i in range(0, len(workers)):
  313. for stat in stats:
  314. s = workers[i].get_event_stats(stat._name)
  315. if not s == None:
  316. # A task might not be executed on all workers.
  317. stat._duration_time += s._duration_time
  318. stat._count += s._count
  319. # Output statistics.
  320. print("\"Name\",\"Count\",\"Type\",\"Duration\"")
  321. for stat in stats:
  322. stat.show()
  323. # Compute runtime, task, idle, scheduling times and dump them to times.csv
  324. ti_p = tr_p = tt_p = ts_p = 0.0
  325. if dump_time == True:
  326. ti_p, tr_p, tt_p, ts_p = calc_times(stats)
  327. save_times(ti_p, tr_p, tt_p, ts_p)
  328. # Compute runtime, task, idle efficiencies and dump them to
  329. # efficiencies.csv.
  330. if dump_efficiency == True or not tt_1 == 0.0:
  331. if dump_time == False:
  332. ti_p, tr_p, tt_p, ts_p = calc_times(stats)
  333. if tt_1 == 0.0:
  334. sys.stderr.write("WARNING: Task efficiency will be 1.0 because -s is not set!\n")
  335. tt_1 = tt_p
  336. # Compute efficiencies.
  337. et = round(calc_et(tt_1, tt_p), 6)
  338. es = round(calc_es(tt_p, ts_p), 6)
  339. er = round(calc_er(tt_p, tr_p, ts_p), 6)
  340. ep = round(calc_ep(tt_p, tr_p, ti_p, ts_p), 6)
  341. e = round(calc_e(et, er, ep, es), 6)
  342. save_efficiencies(e, ep, er, et, es)
  343. if __name__ == "__main__":
  344. main()