starpu_trace_state_stats.py 14 KB

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