kmp_stats.h 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. #ifndef KMP_STATS_H
  2. #define KMP_STATS_H
  3. /** @file kmp_stats.h
  4. * Functions for collecting statistics.
  5. */
  6. //===----------------------------------------------------------------------===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "kmp_config.h"
  14. #include "kmp_debug.h"
  15. #if KMP_STATS_ENABLED
  16. /* Statistics accumulator.
  17. Accumulates number of samples and computes min, max, mean, standard deviation
  18. on the fly.
  19. Online variance calculation algorithm from
  20. http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm
  21. */
  22. #error #include "kmp_stats_timing.h"
  23. #include <limits>
  24. #include <math.h>
  25. #include <new> // placement new
  26. #include <stdint.h>
  27. #include <string>
  28. #include <vector>
  29. /* Enable developer statistics here if you want them. They are more detailed
  30. than is useful for application characterisation and are intended for the
  31. runtime library developer. */
  32. #define KMP_DEVELOPER_STATS 0
  33. /* Enable/Disable histogram output */
  34. #define KMP_STATS_HIST 0
  35. /*!
  36. * @ingroup STATS_GATHERING
  37. * \brief flags to describe the statistic (timer or counter)
  38. *
  39. */
  40. enum stats_flags_e {
  41. noTotal = 1 << 0, //!< do not show a TOTAL_aggregation for this statistic
  42. onlyInMaster = 1 << 1, //!< statistic is valid only for primary thread
  43. noUnits = 1 << 2, //!< statistic doesn't need units printed next to it
  44. notInMaster = 1 << 3, //!< statistic is valid only for non-primary threads
  45. logEvent = 1 << 4 //!< statistic can be logged on the event timeline when
  46. //! KMP_STATS_EVENTS is on (valid only for timers)
  47. };
  48. /*!
  49. * @ingroup STATS_GATHERING
  50. * \brief the states which a thread can be in
  51. *
  52. */
  53. enum stats_state_e {
  54. IDLE,
  55. SERIAL_REGION,
  56. FORK_JOIN_BARRIER,
  57. PLAIN_BARRIER,
  58. TASKWAIT,
  59. TASKYIELD,
  60. TASKGROUP,
  61. IMPLICIT_TASK,
  62. EXPLICIT_TASK,
  63. TEAMS_REGION
  64. };
  65. /*!
  66. * \brief Add new counters under KMP_FOREACH_COUNTER() macro in kmp_stats.h
  67. *
  68. * @param macro a user defined macro that takes three arguments -
  69. * macro(COUNTER_NAME, flags, arg)
  70. * @param arg a user defined argument to send to the user defined macro
  71. *
  72. * \details A counter counts the occurrence of some event. Each thread
  73. * accumulates its own count, at the end of execution the counts are aggregated
  74. * treating each thread as a separate measurement. (Unless onlyInMaster is set,
  75. * in which case there's only a single measurement). The min,mean,max are
  76. * therefore the values for the threads. Adding the counter here and then
  77. * putting a KMP_BLOCK_COUNTER(name) at the point you want to count is all you
  78. * need to do. All of the tables and printing is generated from this macro.
  79. * Format is "macro(name, flags, arg)"
  80. *
  81. * @ingroup STATS_GATHERING
  82. */
  83. // clang-format off
  84. #define KMP_FOREACH_COUNTER(macro, arg) \
  85. macro(OMP_PARALLEL,stats_flags_e::onlyInMaster|stats_flags_e::noTotal,arg) \
  86. macro(OMP_NESTED_PARALLEL, 0, arg) \
  87. macro(OMP_LOOP_STATIC, 0, arg) \
  88. macro(OMP_LOOP_STATIC_STEAL, 0, arg) \
  89. macro(OMP_LOOP_DYNAMIC, 0, arg) \
  90. macro(OMP_DISTRIBUTE, 0, arg) \
  91. macro(OMP_BARRIER, 0, arg) \
  92. macro(OMP_CRITICAL, 0, arg) \
  93. macro(OMP_SINGLE, 0, arg) \
  94. macro(OMP_MASTER, 0, arg) \
  95. macro(OMP_MASKED, 0, arg) \
  96. macro(OMP_TEAMS, 0, arg) \
  97. macro(OMP_set_lock, 0, arg) \
  98. macro(OMP_test_lock, 0, arg) \
  99. macro(REDUCE_wait, 0, arg) \
  100. macro(REDUCE_nowait, 0, arg) \
  101. macro(OMP_TASKYIELD, 0, arg) \
  102. macro(OMP_TASKLOOP, 0, arg) \
  103. macro(TASK_executed, 0, arg) \
  104. macro(TASK_cancelled, 0, arg) \
  105. macro(TASK_stolen, 0, arg)
  106. // clang-format on
  107. /*!
  108. * \brief Add new timers under KMP_FOREACH_TIMER() macro in kmp_stats.h
  109. *
  110. * @param macro a user defined macro that takes three arguments -
  111. * macro(TIMER_NAME, flags, arg)
  112. * @param arg a user defined argument to send to the user defined macro
  113. *
  114. * \details A timer collects multiple samples of some count in each thread and
  115. * then finally aggregates all of the samples from all of the threads. For most
  116. * timers the printing code also provides an aggregation over the thread totals.
  117. * These are printed as TOTAL_foo. The count is normally a time (in ticks),
  118. * hence the name "timer". (But can be any value, so we use this for "number of
  119. * arguments passed to fork" as well). For timers the threads are not
  120. * significant, it's the individual observations that count, so the statistics
  121. * are at that level. Format is "macro(name, flags, arg)"
  122. *
  123. * @ingroup STATS_GATHERING2
  124. */
  125. // clang-format off
  126. #define KMP_FOREACH_TIMER(macro, arg) \
  127. macro (OMP_worker_thread_life, stats_flags_e::logEvent, arg) \
  128. macro (OMP_parallel, stats_flags_e::logEvent, arg) \
  129. macro (OMP_parallel_overhead, stats_flags_e::logEvent, arg) \
  130. macro (OMP_teams, stats_flags_e::logEvent, arg) \
  131. macro (OMP_teams_overhead, stats_flags_e::logEvent, arg) \
  132. macro (OMP_loop_static, 0, arg) \
  133. macro (OMP_loop_static_scheduling, 0, arg) \
  134. macro (OMP_loop_dynamic, 0, arg) \
  135. macro (OMP_loop_dynamic_scheduling, 0, arg) \
  136. macro (OMP_distribute, 0, arg) \
  137. macro (OMP_distribute_scheduling, 0, arg) \
  138. macro (OMP_critical, 0, arg) \
  139. macro (OMP_critical_wait, 0, arg) \
  140. macro (OMP_single, 0, arg) \
  141. macro (OMP_master, 0, arg) \
  142. macro (OMP_masked, 0, arg) \
  143. macro (OMP_task_immediate, 0, arg) \
  144. macro (OMP_task_taskwait, 0, arg) \
  145. macro (OMP_task_taskyield, 0, arg) \
  146. macro (OMP_task_taskgroup, 0, arg) \
  147. macro (OMP_task_join_bar, 0, arg) \
  148. macro (OMP_task_plain_bar, 0, arg) \
  149. macro (OMP_taskloop_scheduling, 0, arg) \
  150. macro (OMP_plain_barrier, stats_flags_e::logEvent, arg) \
  151. macro (OMP_idle, stats_flags_e::logEvent, arg) \
  152. macro (OMP_fork_barrier, stats_flags_e::logEvent, arg) \
  153. macro (OMP_join_barrier, stats_flags_e::logEvent, arg) \
  154. macro (OMP_serial, stats_flags_e::logEvent, arg) \
  155. macro (OMP_set_numthreads, stats_flags_e::noUnits | stats_flags_e::noTotal, \
  156. arg) \
  157. macro (OMP_PARALLEL_args, stats_flags_e::noUnits | stats_flags_e::noTotal, \
  158. arg) \
  159. macro (OMP_loop_static_iterations, \
  160. stats_flags_e::noUnits | stats_flags_e::noTotal, arg) \
  161. macro (OMP_loop_static_total_iterations, \
  162. stats_flags_e::noUnits | stats_flags_e::noTotal, arg) \
  163. macro (OMP_loop_dynamic_iterations, \
  164. stats_flags_e::noUnits | stats_flags_e::noTotal, arg) \
  165. macro (OMP_loop_dynamic_total_iterations, \
  166. stats_flags_e::noUnits | stats_flags_e::noTotal, arg) \
  167. macro (OMP_distribute_iterations, \
  168. stats_flags_e::noUnits | stats_flags_e::noTotal, arg) \
  169. KMP_FOREACH_DEVELOPER_TIMER(macro, arg)
  170. // clang-format on
  171. // OMP_worker_thread_life -- Time from thread becoming an OpenMP thread (either
  172. // initializing OpenMP or being created by a primary
  173. // thread) until the thread is destroyed
  174. // OMP_parallel -- Time thread spends executing work directly
  175. // within a #pragma omp parallel
  176. // OMP_parallel_overhead -- Time thread spends setting up a parallel region
  177. // OMP_loop_static -- Time thread spends executing loop iterations from
  178. // a statically scheduled loop
  179. // OMP_loop_static_scheduling -- Time thread spends scheduling loop iterations
  180. // from a statically scheduled loop
  181. // OMP_loop_dynamic -- Time thread spends executing loop iterations from
  182. // a dynamically scheduled loop
  183. // OMP_loop_dynamic_scheduling -- Time thread spends scheduling loop iterations
  184. // from a dynamically scheduled loop
  185. // OMP_critical -- Time thread spends executing critical section
  186. // OMP_critical_wait -- Time thread spends waiting to enter
  187. // a critical section
  188. // OMP_single -- Time spent executing a "single" region
  189. // OMP_master -- Time spent executing a "master" region
  190. // OMP_masked -- Time spent executing a "masked" region
  191. // OMP_task_immediate -- Time spent executing non-deferred tasks
  192. // OMP_task_taskwait -- Time spent executing tasks inside a taskwait
  193. // construct
  194. // OMP_task_taskyield -- Time spent executing tasks inside a taskyield
  195. // construct
  196. // OMP_task_taskgroup -- Time spent executing tasks inside a taskygroup
  197. // construct
  198. // OMP_task_join_bar -- Time spent executing tasks inside a join barrier
  199. // OMP_task_plain_bar -- Time spent executing tasks inside a barrier
  200. // construct
  201. // OMP_taskloop_scheduling -- Time spent scheduling tasks inside a taskloop
  202. // construct
  203. // OMP_plain_barrier -- Time spent in a #pragma omp barrier construct or
  204. // inside implicit barrier at end of worksharing
  205. // construct
  206. // OMP_idle -- Time worker threads spend waiting for next
  207. // parallel region
  208. // OMP_fork_barrier -- Time spent in a the fork barrier surrounding a
  209. // parallel region
  210. // OMP_join_barrier -- Time spent in a the join barrier surrounding a
  211. // parallel region
  212. // OMP_serial -- Time thread zero spends executing serial code
  213. // OMP_set_numthreads -- Values passed to omp_set_num_threads
  214. // OMP_PARALLEL_args -- Number of arguments passed to a parallel region
  215. // OMP_loop_static_iterations -- Number of iterations thread is assigned for
  216. // statically scheduled loops
  217. // OMP_loop_dynamic_iterations -- Number of iterations thread is assigned for
  218. // dynamically scheduled loops
  219. #if (KMP_DEVELOPER_STATS)
  220. // Timers which are of interest to runtime library developers, not end users.
  221. // These have to be explicitly enabled in addition to the other stats.
  222. // KMP_fork_barrier -- time in __kmp_fork_barrier
  223. // KMP_join_barrier -- time in __kmp_join_barrier
  224. // KMP_barrier -- time in __kmp_barrier
  225. // KMP_end_split_barrier -- time in __kmp_end_split_barrier
  226. // KMP_setup_icv_copy -- time in __kmp_setup_icv_copy
  227. // KMP_icv_copy -- start/stop timer for any ICV copying
  228. // KMP_linear_gather -- time in __kmp_linear_barrier_gather
  229. // KMP_linear_release -- time in __kmp_linear_barrier_release
  230. // KMP_tree_gather -- time in __kmp_tree_barrier_gather
  231. // KMP_tree_release -- time in __kmp_tree_barrier_release
  232. // KMP_hyper_gather -- time in __kmp_hyper_barrier_gather
  233. // KMP_hyper_release -- time in __kmp_hyper_barrier_release
  234. // KMP_dist_gather -- time in __kmp_dist_barrier_gather
  235. // KMP_dist_release -- time in __kmp_dist_barrier_release
  236. // clang-format off
  237. #define KMP_FOREACH_DEVELOPER_TIMER(macro, arg) \
  238. macro(KMP_fork_call, 0, arg) \
  239. macro(KMP_join_call, 0, arg) \
  240. macro(KMP_end_split_barrier, 0, arg) \
  241. macro(KMP_hier_gather, 0, arg) \
  242. macro(KMP_hier_release, 0, arg) \
  243. macro(KMP_hyper_gather, 0, arg) \
  244. macro(KMP_hyper_release, 0, arg) \
  245. macro(KMP_dist_gather, 0, arg) \
  246. macro(KMP_dist_release, 0, arg) \
  247. macro(KMP_linear_gather, 0, arg) \
  248. macro(KMP_linear_release, 0, arg) \
  249. macro(KMP_tree_gather, 0, arg) \
  250. macro(KMP_tree_release, 0, arg) \
  251. macro(USER_resume, 0, arg) \
  252. macro(USER_suspend, 0, arg) \
  253. macro(USER_mwait, 0, arg) \
  254. macro(KMP_allocate_team, 0, arg) \
  255. macro(KMP_setup_icv_copy, 0, arg) \
  256. macro(USER_icv_copy, 0, arg) \
  257. macro (FOR_static_steal_stolen, \
  258. stats_flags_e::noUnits | stats_flags_e::noTotal, arg) \
  259. macro (FOR_static_steal_chunks, \
  260. stats_flags_e::noUnits | stats_flags_e::noTotal, arg)
  261. #else
  262. #define KMP_FOREACH_DEVELOPER_TIMER(macro, arg)
  263. #endif
  264. // clang-format on
  265. /*!
  266. * \brief Add new explicit timers under KMP_FOREACH_EXPLICIT_TIMER() macro.
  267. *
  268. * @param macro a user defined macro that takes three arguments -
  269. * macro(TIMER_NAME, flags, arg)
  270. * @param arg a user defined argument to send to the user defined macro
  271. *
  272. * \warning YOU MUST HAVE THE SAME NAMED TIMER UNDER KMP_FOREACH_TIMER() OR ELSE
  273. * BAD THINGS WILL HAPPEN!
  274. *
  275. * \details Explicit timers are ones where we need to allocate a timer itself
  276. * (as well as the accumulated timing statistics). We allocate these on a
  277. * per-thread basis, and explicitly start and stop them. Block timers just
  278. * allocate the timer itself on the stack, and use the destructor to notice
  279. * block exit; they don't need to be defined here. The name here should be the
  280. * same as that of a timer above.
  281. *
  282. * @ingroup STATS_GATHERING
  283. */
  284. #define KMP_FOREACH_EXPLICIT_TIMER(macro, arg) KMP_FOREACH_TIMER(macro, arg)
  285. #define ENUMERATE(name, ignore, prefix) prefix##name,
  286. enum timer_e { KMP_FOREACH_TIMER(ENUMERATE, TIMER_) TIMER_LAST };
  287. enum explicit_timer_e {
  288. KMP_FOREACH_EXPLICIT_TIMER(ENUMERATE, EXPLICIT_TIMER_) EXPLICIT_TIMER_LAST
  289. };
  290. enum counter_e { KMP_FOREACH_COUNTER(ENUMERATE, COUNTER_) COUNTER_LAST };
  291. #undef ENUMERATE
  292. /*
  293. * A logarithmic histogram. It accumulates the number of values in each power of
  294. * ten bin. So 1<=x<10, 10<=x<100, ...
  295. * Mostly useful where we have some big outliers and want to see information
  296. * about them.
  297. */
  298. class logHistogram {
  299. enum {
  300. numBins = 31, /* Number of powers of 10. If this changes you need to change
  301. * the initializer for binMax */
  302. /*
  303. * If you want to use this to analyse values that may be less than 1, (for
  304. * instance times in s), then the logOffset gives you negative powers.
  305. * In our case here, we're just looking at times in ticks, or counts, so we
  306. * can never see values with magnitude < 1 (other than zero), so we can set
  307. * it to 0. As above change the initializer if you change this.
  308. */
  309. logOffset = 0
  310. };
  311. uint32_t KMP_ALIGN_CACHE zeroCount;
  312. struct {
  313. uint32_t count;
  314. double total;
  315. } bins[numBins];
  316. static double binMax[numBins];
  317. #ifdef KMP_DEBUG
  318. uint64_t _total;
  319. void check() const {
  320. uint64_t t = zeroCount;
  321. for (int i = 0; i < numBins; i++)
  322. t += bins[i].count;
  323. KMP_DEBUG_ASSERT(t == _total);
  324. }
  325. #else
  326. void check() const {}
  327. #endif
  328. public:
  329. logHistogram() { reset(); }
  330. logHistogram(logHistogram const &o) {
  331. for (int i = 0; i < numBins; i++)
  332. bins[i] = o.bins[i];
  333. #ifdef KMP_DEBUG
  334. _total = o._total;
  335. #endif
  336. }
  337. void reset() {
  338. zeroCount = 0;
  339. for (int i = 0; i < numBins; i++) {
  340. bins[i].count = 0;
  341. bins[i].total = 0;
  342. }
  343. #ifdef KMP_DEBUG
  344. _total = 0;
  345. #endif
  346. }
  347. uint32_t count(int b) const { return bins[b + logOffset].count; }
  348. double total(int b) const { return bins[b + logOffset].total; }
  349. static uint32_t findBin(double sample);
  350. logHistogram &operator+=(logHistogram const &o) {
  351. zeroCount += o.zeroCount;
  352. for (int i = 0; i < numBins; i++) {
  353. bins[i].count += o.bins[i].count;
  354. bins[i].total += o.bins[i].total;
  355. }
  356. #ifdef KMP_DEBUG
  357. _total += o._total;
  358. check();
  359. #endif
  360. return *this;
  361. }
  362. void addSample(double sample);
  363. int minBin() const;
  364. int maxBin() const;
  365. std::string format(char) const;
  366. };
  367. class statistic {
  368. double KMP_ALIGN_CACHE minVal;
  369. double maxVal;
  370. double meanVal;
  371. double m2;
  372. uint64_t sampleCount;
  373. double offset;
  374. bool collectingHist;
  375. logHistogram hist;
  376. public:
  377. statistic(bool doHist = bool(KMP_STATS_HIST)) {
  378. reset();
  379. collectingHist = doHist;
  380. }
  381. statistic(statistic const &o)
  382. : minVal(o.minVal), maxVal(o.maxVal), meanVal(o.meanVal), m2(o.m2),
  383. sampleCount(o.sampleCount), offset(o.offset),
  384. collectingHist(o.collectingHist), hist(o.hist) {}
  385. statistic(double minv, double maxv, double meanv, uint64_t sc, double sd)
  386. : minVal(minv), maxVal(maxv), meanVal(meanv), m2(sd * sd * sc),
  387. sampleCount(sc), offset(0.0), collectingHist(false) {}
  388. bool haveHist() const { return collectingHist; }
  389. double getMin() const { return minVal; }
  390. double getMean() const { return meanVal; }
  391. double getMax() const { return maxVal; }
  392. uint64_t getCount() const { return sampleCount; }
  393. double getSD() const { return sqrt(m2 / sampleCount); }
  394. double getTotal() const { return sampleCount * meanVal; }
  395. logHistogram const *getHist() const { return &hist; }
  396. void setOffset(double d) { offset = d; }
  397. void reset() {
  398. minVal = (std::numeric_limits<double>::max)();
  399. maxVal = -minVal;
  400. meanVal = 0.0;
  401. m2 = 0.0;
  402. sampleCount = 0;
  403. offset = 0.0;
  404. hist.reset();
  405. }
  406. void addSample(double sample);
  407. void scale(double factor);
  408. void scaleDown(double f) { scale(1. / f); }
  409. void forceCount(uint64_t count) { sampleCount = count; }
  410. statistic &operator+=(statistic const &other);
  411. std::string format(char unit, bool total = false) const;
  412. std::string formatHist(char unit) const { return hist.format(unit); }
  413. };
  414. struct statInfo {
  415. const char *name;
  416. uint32_t flags;
  417. };
  418. class timeStat : public statistic {
  419. static statInfo timerInfo[];
  420. public:
  421. timeStat() : statistic() {}
  422. static const char *name(timer_e e) { return timerInfo[e].name; }
  423. static bool noTotal(timer_e e) {
  424. return timerInfo[e].flags & stats_flags_e::noTotal;
  425. }
  426. static bool masterOnly(timer_e e) {
  427. return timerInfo[e].flags & stats_flags_e::onlyInMaster;
  428. }
  429. static bool workerOnly(timer_e e) {
  430. return timerInfo[e].flags & stats_flags_e::notInMaster;
  431. }
  432. static bool noUnits(timer_e e) {
  433. return timerInfo[e].flags & stats_flags_e::noUnits;
  434. }
  435. static bool logEvent(timer_e e) {
  436. return timerInfo[e].flags & stats_flags_e::logEvent;
  437. }
  438. static void clearEventFlags() {
  439. for (int i = 0; i < TIMER_LAST; i++) {
  440. timerInfo[i].flags &= (~(stats_flags_e::logEvent));
  441. }
  442. }
  443. };
  444. // Where we need explicitly to start and end the timer, this version can be used
  445. // Since these timers normally aren't nicely scoped, so don't have a good place
  446. // to live on the stack of the thread, they're more work to use.
  447. class explicitTimer {
  448. timeStat *stat;
  449. timer_e timerEnumValue;
  450. tsc_tick_count startTime;
  451. tsc_tick_count pauseStartTime;
  452. tsc_tick_count::tsc_interval_t totalPauseTime;
  453. public:
  454. explicitTimer(timeStat *s, timer_e te)
  455. : stat(s), timerEnumValue(te), startTime(), pauseStartTime(0),
  456. totalPauseTime() {}
  457. // void setStat(timeStat *s) { stat = s; }
  458. void start(tsc_tick_count tick);
  459. void pause(tsc_tick_count tick) { pauseStartTime = tick; }
  460. void resume(tsc_tick_count tick) {
  461. totalPauseTime += (tick - pauseStartTime);
  462. }
  463. void stop(tsc_tick_count tick, kmp_stats_list *stats_ptr = nullptr);
  464. void reset() {
  465. startTime = 0;
  466. pauseStartTime = 0;
  467. totalPauseTime = 0;
  468. }
  469. timer_e get_type() const { return timerEnumValue; }
  470. };
  471. // Where you need to partition a threads clock ticks into separate states
  472. // e.g., a partitionedTimers class with two timers of EXECUTING_TASK, and
  473. // DOING_NOTHING would render these conditions:
  474. // time(EXECUTING_TASK) + time(DOING_NOTHING) = total time thread is alive
  475. // No clock tick in the EXECUTING_TASK is a member of DOING_NOTHING and vice
  476. // versa
  477. class partitionedTimers {
  478. private:
  479. std::vector<explicitTimer> timer_stack;
  480. public:
  481. partitionedTimers();
  482. void init(explicitTimer timer);
  483. void exchange(explicitTimer timer);
  484. void push(explicitTimer timer);
  485. void pop();
  486. void windup();
  487. };
  488. // Special wrapper around the partitioned timers to aid timing code blocks
  489. // It avoids the need to have an explicit end, leaving the scope suffices.
  490. class blockPartitionedTimer {
  491. partitionedTimers *part_timers;
  492. public:
  493. blockPartitionedTimer(partitionedTimers *pt, explicitTimer timer)
  494. : part_timers(pt) {
  495. part_timers->push(timer);
  496. }
  497. ~blockPartitionedTimer() { part_timers->pop(); }
  498. };
  499. // Special wrapper around the thread state to aid in keeping state in code
  500. // blocks It avoids the need to have an explicit end, leaving the scope
  501. // suffices.
  502. class blockThreadState {
  503. stats_state_e *state_pointer;
  504. stats_state_e old_state;
  505. public:
  506. blockThreadState(stats_state_e *thread_state_pointer, stats_state_e new_state)
  507. : state_pointer(thread_state_pointer), old_state(*thread_state_pointer) {
  508. *state_pointer = new_state;
  509. }
  510. ~blockThreadState() { *state_pointer = old_state; }
  511. };
  512. // If all you want is a count, then you can use this...
  513. // The individual per-thread counts will be aggregated into a statistic at
  514. // program exit.
  515. class counter {
  516. uint64_t value;
  517. static const statInfo counterInfo[];
  518. public:
  519. counter() : value(0) {}
  520. void increment() { value++; }
  521. uint64_t getValue() const { return value; }
  522. void reset() { value = 0; }
  523. static const char *name(counter_e e) { return counterInfo[e].name; }
  524. static bool masterOnly(counter_e e) {
  525. return counterInfo[e].flags & stats_flags_e::onlyInMaster;
  526. }
  527. };
  528. /* ****************************************************************
  529. Class to implement an event
  530. There are four components to an event: start time, stop time
  531. nest_level, and timer_name.
  532. The start and stop time should be obvious (recorded in clock ticks).
  533. The nest_level relates to the bar width in the timeline graph.
  534. The timer_name is used to determine which timer event triggered this event.
  535. the interface to this class is through four read-only operations:
  536. 1) getStart() -- returns the start time as 64 bit integer
  537. 2) getStop() -- returns the stop time as 64 bit integer
  538. 3) getNestLevel() -- returns the nest level of the event
  539. 4) getTimerName() -- returns the timer name that triggered event
  540. *MORE ON NEST_LEVEL*
  541. The nest level is used in the bar graph that represents the timeline.
  542. Its main purpose is for showing how events are nested inside eachother.
  543. For example, say events, A, B, and C are recorded. If the timeline
  544. looks like this:
  545. Begin -------------------------------------------------------------> Time
  546. | | | | | |
  547. A B C C B A
  548. start start start end end end
  549. Then A, B, C will have a nest level of 1, 2, 3 respectively.
  550. These values are then used to calculate the barwidth so you can
  551. see that inside A, B has occurred, and inside B, C has occurred.
  552. Currently, this is shown with A's bar width being larger than B's
  553. bar width, and B's bar width being larger than C's bar width.
  554. **************************************************************** */
  555. class kmp_stats_event {
  556. uint64_t start;
  557. uint64_t stop;
  558. int nest_level;
  559. timer_e timer_name;
  560. public:
  561. kmp_stats_event()
  562. : start(0), stop(0), nest_level(0), timer_name(TIMER_LAST) {}
  563. kmp_stats_event(uint64_t strt, uint64_t stp, int nst, timer_e nme)
  564. : start(strt), stop(stp), nest_level(nst), timer_name(nme) {}
  565. inline uint64_t getStart() const { return start; }
  566. inline uint64_t getStop() const { return stop; }
  567. inline int getNestLevel() const { return nest_level; }
  568. inline timer_e getTimerName() const { return timer_name; }
  569. };
  570. /* ****************************************************************
  571. Class to implement a dynamically expandable array of events
  572. ---------------------------------------------------------
  573. | event 1 | event 2 | event 3 | event 4 | ... | event N |
  574. ---------------------------------------------------------
  575. An event is pushed onto the back of this array at every
  576. explicitTimer->stop() call. The event records the thread #,
  577. start time, stop time, and nest level related to the bar width.
  578. The event vector starts at size INIT_SIZE and grows (doubles in size)
  579. if needed. An implication of this behavior is that log(N)
  580. reallocations are needed (where N is number of events). If you want
  581. to avoid reallocations, then set INIT_SIZE to a large value.
  582. the interface to this class is through six operations:
  583. 1) reset() -- sets the internal_size back to 0 but does not deallocate any
  584. memory
  585. 2) size() -- returns the number of valid elements in the vector
  586. 3) push_back(start, stop, nest, timer_name) -- pushes an event onto
  587. the back of the array
  588. 4) deallocate() -- frees all memory associated with the vector
  589. 5) sort() -- sorts the vector by start time
  590. 6) operator[index] or at(index) -- returns event reference at that index
  591. **************************************************************** */
  592. class kmp_stats_event_vector {
  593. kmp_stats_event *events;
  594. int internal_size;
  595. int allocated_size;
  596. static const int INIT_SIZE = 1024;
  597. public:
  598. kmp_stats_event_vector() {
  599. events =
  600. (kmp_stats_event *)__kmp_allocate(sizeof(kmp_stats_event) * INIT_SIZE);
  601. internal_size = 0;
  602. allocated_size = INIT_SIZE;
  603. }
  604. ~kmp_stats_event_vector() {}
  605. inline void reset() { internal_size = 0; }
  606. inline int size() const { return internal_size; }
  607. void push_back(uint64_t start_time, uint64_t stop_time, int nest_level,
  608. timer_e name) {
  609. int i;
  610. if (internal_size == allocated_size) {
  611. kmp_stats_event *tmp = (kmp_stats_event *)__kmp_allocate(
  612. sizeof(kmp_stats_event) * allocated_size * 2);
  613. for (i = 0; i < internal_size; i++)
  614. tmp[i] = events[i];
  615. __kmp_free(events);
  616. events = tmp;
  617. allocated_size *= 2;
  618. }
  619. events[internal_size] =
  620. kmp_stats_event(start_time, stop_time, nest_level, name);
  621. internal_size++;
  622. return;
  623. }
  624. void deallocate();
  625. void sort();
  626. const kmp_stats_event &operator[](int index) const { return events[index]; }
  627. kmp_stats_event &operator[](int index) { return events[index]; }
  628. const kmp_stats_event &at(int index) const { return events[index]; }
  629. kmp_stats_event &at(int index) { return events[index]; }
  630. };
  631. /* ****************************************************************
  632. Class to implement a doubly-linked, circular, statistics list
  633. |---| ---> |---| ---> |---| ---> |---| ---> ... next
  634. | | | | | | | |
  635. |---| <--- |---| <--- |---| <--- |---| <--- ... prev
  636. Sentinel first second third
  637. Node node node node
  638. The Sentinel Node is the user handle on the list.
  639. The first node corresponds to thread 0's statistics.
  640. The second node corresponds to thread 1's statistics and so on...
  641. Each node has a _timers, _counters, and _explicitTimers array to hold that
  642. thread's statistics. The _explicitTimers point to the correct _timer and
  643. update its statistics at every stop() call. The explicitTimers' pointers are
  644. set up in the constructor. Each node also has an event vector to hold that
  645. thread's timing events. The event vector expands as necessary and records
  646. the start-stop times for each timer.
  647. The nestLevel variable is for plotting events and is related
  648. to the bar width in the timeline graph.
  649. Every thread will have a thread local pointer to its node in
  650. the list. The sentinel node is used by the primary thread to
  651. store "dummy" statistics before __kmp_create_worker() is called.
  652. **************************************************************** */
  653. class kmp_stats_list {
  654. int gtid;
  655. timeStat _timers[TIMER_LAST + 1];
  656. counter _counters[COUNTER_LAST + 1];
  657. explicitTimer thread_life_timer;
  658. partitionedTimers _partitionedTimers;
  659. int _nestLevel; // one per thread
  660. kmp_stats_event_vector _event_vector;
  661. kmp_stats_list *next;
  662. kmp_stats_list *prev;
  663. stats_state_e state;
  664. int thread_is_idle_flag;
  665. public:
  666. kmp_stats_list()
  667. : thread_life_timer(&_timers[TIMER_OMP_worker_thread_life],
  668. TIMER_OMP_worker_thread_life),
  669. _nestLevel(0), _event_vector(), next(this), prev(this), state(IDLE),
  670. thread_is_idle_flag(0) {}
  671. ~kmp_stats_list() {}
  672. inline timeStat *getTimer(timer_e idx) { return &_timers[idx]; }
  673. inline counter *getCounter(counter_e idx) { return &_counters[idx]; }
  674. inline partitionedTimers *getPartitionedTimers() {
  675. return &_partitionedTimers;
  676. }
  677. inline timeStat *getTimers() { return _timers; }
  678. inline counter *getCounters() { return _counters; }
  679. inline kmp_stats_event_vector &getEventVector() { return _event_vector; }
  680. inline void startLife() { thread_life_timer.start(tsc_tick_count::now()); }
  681. inline void endLife() { thread_life_timer.stop(tsc_tick_count::now(), this); }
  682. inline void resetEventVector() { _event_vector.reset(); }
  683. inline void incrementNestValue() { _nestLevel++; }
  684. inline int getNestValue() { return _nestLevel; }
  685. inline void decrementNestValue() { _nestLevel--; }
  686. inline int getGtid() const { return gtid; }
  687. inline void setGtid(int newgtid) { gtid = newgtid; }
  688. inline void setState(stats_state_e newstate) { state = newstate; }
  689. inline stats_state_e getState() const { return state; }
  690. inline stats_state_e *getStatePointer() { return &state; }
  691. inline bool isIdle() { return thread_is_idle_flag == 1; }
  692. inline void setIdleFlag() { thread_is_idle_flag = 1; }
  693. inline void resetIdleFlag() { thread_is_idle_flag = 0; }
  694. kmp_stats_list *push_back(int gtid); // returns newly created list node
  695. inline void push_event(uint64_t start_time, uint64_t stop_time,
  696. int nest_level, timer_e name) {
  697. _event_vector.push_back(start_time, stop_time, nest_level, name);
  698. }
  699. void deallocate();
  700. class iterator;
  701. kmp_stats_list::iterator begin();
  702. kmp_stats_list::iterator end();
  703. int size();
  704. class iterator {
  705. kmp_stats_list *ptr;
  706. friend kmp_stats_list::iterator kmp_stats_list::begin();
  707. friend kmp_stats_list::iterator kmp_stats_list::end();
  708. public:
  709. iterator();
  710. ~iterator();
  711. iterator operator++();
  712. iterator operator++(int dummy);
  713. iterator operator--();
  714. iterator operator--(int dummy);
  715. bool operator!=(const iterator &rhs);
  716. bool operator==(const iterator &rhs);
  717. kmp_stats_list *operator*() const; // dereference operator
  718. };
  719. };
  720. /* ****************************************************************
  721. Class to encapsulate all output functions and the environment variables
  722. This module holds filenames for various outputs (normal stats, events, plot
  723. file), as well as coloring information for the plot file.
  724. The filenames and flags variables are read from environment variables.
  725. These are read once by the constructor of the global variable
  726. __kmp_stats_output which calls init().
  727. During this init() call, event flags for the timeStat::timerInfo[] global
  728. array are cleared if KMP_STATS_EVENTS is not true (on, 1, yes).
  729. The only interface function that is public is outputStats(heading). This
  730. function should print out everything it needs to, either to files or stderr,
  731. depending on the environment variables described below
  732. ENVIRONMENT VARIABLES:
  733. KMP_STATS_FILE -- if set, all statistics (not events) will be printed to this
  734. file, otherwise, print to stderr
  735. KMP_STATS_THREADS -- if set to "on", then will print per thread statistics to
  736. either KMP_STATS_FILE or stderr
  737. KMP_STATS_PLOT_FILE -- if set, print the ploticus plot file to this filename,
  738. otherwise, the plot file is sent to "events.plt"
  739. KMP_STATS_EVENTS -- if set to "on", then log events, otherwise, don't log
  740. events
  741. KMP_STATS_EVENTS_FILE -- if set, all events are outputted to this file,
  742. otherwise, output is sent to "events.dat"
  743. **************************************************************** */
  744. class kmp_stats_output_module {
  745. public:
  746. struct rgb_color {
  747. float r;
  748. float g;
  749. float b;
  750. };
  751. private:
  752. std::string outputFileName;
  753. static const char *eventsFileName;
  754. static const char *plotFileName;
  755. static int printPerThreadFlag;
  756. static int printPerThreadEventsFlag;
  757. static const rgb_color globalColorArray[];
  758. static rgb_color timerColorInfo[];
  759. void init();
  760. static void setupEventColors();
  761. static void printPloticusFile();
  762. static void printHeaderInfo(FILE *statsOut);
  763. static void printTimerStats(FILE *statsOut, statistic const *theStats,
  764. statistic const *totalStats);
  765. static void printCounterStats(FILE *statsOut, statistic const *theStats);
  766. static void printCounters(FILE *statsOut, counter const *theCounters);
  767. static void printEvents(FILE *eventsOut, kmp_stats_event_vector *theEvents,
  768. int gtid);
  769. static rgb_color getEventColor(timer_e e) { return timerColorInfo[e]; }
  770. static void windupExplicitTimers();
  771. bool eventPrintingEnabled() const { return printPerThreadEventsFlag; }
  772. public:
  773. kmp_stats_output_module() { init(); }
  774. void outputStats(const char *heading);
  775. };
  776. #ifdef __cplusplus
  777. extern "C" {
  778. #endif
  779. void __kmp_stats_init();
  780. void __kmp_stats_fini();
  781. void __kmp_reset_stats();
  782. void __kmp_output_stats(const char *);
  783. void __kmp_accumulate_stats_at_exit(void);
  784. // thread local pointer to stats node within list
  785. extern KMP_THREAD_LOCAL kmp_stats_list *__kmp_stats_thread_ptr;
  786. // head to stats list.
  787. extern kmp_stats_list *__kmp_stats_list;
  788. // lock for __kmp_stats_list
  789. extern kmp_tas_lock_t __kmp_stats_lock;
  790. // reference start time
  791. extern tsc_tick_count __kmp_stats_start_time;
  792. // interface to output
  793. extern kmp_stats_output_module __kmp_stats_output;
  794. #ifdef __cplusplus
  795. }
  796. #endif
  797. // Simple, standard interfaces that drop out completely if stats aren't enabled
  798. /*!
  799. * \brief Adds value to specified timer (name).
  800. *
  801. * @param name timer name as specified under the KMP_FOREACH_TIMER() macro
  802. * @param value double precision sample value to add to statistics for the timer
  803. *
  804. * \details Use KMP_COUNT_VALUE(name, value) macro to add a particular value to
  805. * a timer statistics.
  806. *
  807. * @ingroup STATS_GATHERING
  808. */
  809. #define KMP_COUNT_VALUE(name, value) \
  810. __kmp_stats_thread_ptr->getTimer(TIMER_##name)->addSample((double)value)
  811. /*!
  812. * \brief Increments specified counter (name).
  813. *
  814. * @param name counter name as specified under the KMP_FOREACH_COUNTER() macro
  815. *
  816. * \details Use KMP_COUNT_BLOCK(name, value) macro to increment a statistics
  817. * counter for the executing thread.
  818. *
  819. * @ingroup STATS_GATHERING
  820. */
  821. #define KMP_COUNT_BLOCK(name) \
  822. __kmp_stats_thread_ptr->getCounter(COUNTER_##name)->increment()
  823. /*!
  824. * \brief Outputs the current thread statistics and reset them.
  825. *
  826. * @param heading_string heading put above the final stats output
  827. *
  828. * \details Explicitly stops all timers and outputs all stats. Environment
  829. * variable, `OMPTB_STATSFILE=filename`, can be used to output the stats to a
  830. * filename instead of stderr. Environment variable,
  831. * `OMPTB_STATSTHREADS=true|undefined`, can be used to output thread specific
  832. * stats. For now the `OMPTB_STATSTHREADS` environment variable can either be
  833. * defined with any value, which will print out thread specific stats, or it can
  834. * be undefined (not specified in the environment) and thread specific stats
  835. * won't be printed. It should be noted that all statistics are reset when this
  836. * macro is called.
  837. *
  838. * @ingroup STATS_GATHERING
  839. */
  840. #define KMP_OUTPUT_STATS(heading_string) __kmp_output_stats(heading_string)
  841. /*!
  842. * \brief Initializes the partitioned timers to begin with name.
  843. *
  844. * @param name timer which you want this thread to begin with
  845. *
  846. * @ingroup STATS_GATHERING
  847. */
  848. #define KMP_INIT_PARTITIONED_TIMERS(name) \
  849. __kmp_stats_thread_ptr->getPartitionedTimers()->init(explicitTimer( \
  850. __kmp_stats_thread_ptr->getTimer(TIMER_##name), TIMER_##name))
  851. #define KMP_TIME_PARTITIONED_BLOCK(name) \
  852. blockPartitionedTimer __PBLOCKTIME__( \
  853. __kmp_stats_thread_ptr->getPartitionedTimers(), \
  854. explicitTimer(__kmp_stats_thread_ptr->getTimer(TIMER_##name), \
  855. TIMER_##name))
  856. #define KMP_PUSH_PARTITIONED_TIMER(name) \
  857. __kmp_stats_thread_ptr->getPartitionedTimers()->push(explicitTimer( \
  858. __kmp_stats_thread_ptr->getTimer(TIMER_##name), TIMER_##name))
  859. #define KMP_POP_PARTITIONED_TIMER() \
  860. __kmp_stats_thread_ptr->getPartitionedTimers()->pop()
  861. #define KMP_EXCHANGE_PARTITIONED_TIMER(name) \
  862. __kmp_stats_thread_ptr->getPartitionedTimers()->exchange(explicitTimer( \
  863. __kmp_stats_thread_ptr->getTimer(TIMER_##name), TIMER_##name))
  864. #define KMP_SET_THREAD_STATE(state_name) \
  865. __kmp_stats_thread_ptr->setState(state_name)
  866. #define KMP_GET_THREAD_STATE() __kmp_stats_thread_ptr->getState()
  867. #define KMP_SET_THREAD_STATE_BLOCK(state_name) \
  868. blockThreadState __BTHREADSTATE__(__kmp_stats_thread_ptr->getStatePointer(), \
  869. state_name)
  870. /*!
  871. * \brief resets all stats (counters to 0, timers to 0 elapsed ticks)
  872. *
  873. * \details Reset all stats for all threads.
  874. *
  875. * @ingroup STATS_GATHERING
  876. */
  877. #define KMP_RESET_STATS() __kmp_reset_stats()
  878. #if (KMP_DEVELOPER_STATS)
  879. #define KMP_COUNT_DEVELOPER_VALUE(n, v) KMP_COUNT_VALUE(n, v)
  880. #define KMP_COUNT_DEVELOPER_BLOCK(n) KMP_COUNT_BLOCK(n)
  881. #define KMP_TIME_DEVELOPER_PARTITIONED_BLOCK(n) KMP_TIME_PARTITIONED_BLOCK(n)
  882. #define KMP_PUSH_DEVELOPER_PARTITIONED_TIMER(n) KMP_PUSH_PARTITIONED_TIMER(n)
  883. #define KMP_POP_DEVELOPER_PARTITIONED_TIMER(n) KMP_POP_PARTITIONED_TIMER(n)
  884. #define KMP_EXCHANGE_DEVELOPER_PARTITIONED_TIMER(n) \
  885. KMP_EXCHANGE_PARTITIONED_TIMER(n)
  886. #else
  887. // Null definitions
  888. #define KMP_COUNT_DEVELOPER_VALUE(n, v) ((void)0)
  889. #define KMP_COUNT_DEVELOPER_BLOCK(n) ((void)0)
  890. #define KMP_TIME_DEVELOPER_PARTITIONED_BLOCK(n) ((void)0)
  891. #define KMP_PUSH_DEVELOPER_PARTITIONED_TIMER(n) ((void)0)
  892. #define KMP_POP_DEVELOPER_PARTITIONED_TIMER(n) ((void)0)
  893. #define KMP_EXCHANGE_DEVELOPER_PARTITIONED_TIMER(n) ((void)0)
  894. #endif
  895. #else // KMP_STATS_ENABLED
  896. // Null definitions
  897. #define KMP_COUNT_VALUE(n, v) ((void)0)
  898. #define KMP_COUNT_BLOCK(n) ((void)0)
  899. #define KMP_OUTPUT_STATS(heading_string) ((void)0)
  900. #define KMP_RESET_STATS() ((void)0)
  901. #define KMP_COUNT_DEVELOPER_VALUE(n, v) ((void)0)
  902. #define KMP_COUNT_DEVELOPER_BLOCK(n) ((void)0)
  903. #define KMP_TIME_DEVELOPER_PARTITIONED_BLOCK(n) ((void)0)
  904. #define KMP_PUSH_DEVELOPER_PARTITIONED_TIMER(n) ((void)0)
  905. #define KMP_POP_DEVELOPER_PARTITIONED_TIMER(n) ((void)0)
  906. #define KMP_EXCHANGE_DEVELOPER_PARTITIONED_TIMER(n) ((void)0)
  907. #define KMP_INIT_PARTITIONED_TIMERS(name) ((void)0)
  908. #define KMP_TIME_PARTITIONED_BLOCK(name) ((void)0)
  909. #define KMP_PUSH_PARTITIONED_TIMER(name) ((void)0)
  910. #define KMP_POP_PARTITIONED_TIMER() ((void)0)
  911. #define KMP_SET_THREAD_STATE(state_name) ((void)0)
  912. #define KMP_GET_THREAD_STATE() ((void)0)
  913. #define KMP_SET_THREAD_STATE_BLOCK(state_name) ((void)0)
  914. #endif // KMP_STATS_ENABLED
  915. #endif // KMP_STATS_H