Timer.h 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-- llvm/Support/Timer.h - Interval Timing Support ----------*- C++ -*-===//
  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. #ifndef LLVM_SUPPORT_TIMER_H
  14. #define LLVM_SUPPORT_TIMER_H
  15. #include "llvm/ADT/StringMap.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/Support/DataTypes.h"
  18. #include <cassert>
  19. #include <memory>
  20. #include <string>
  21. #include <vector>
  22. namespace llvm {
  23. class TimerGroup;
  24. class raw_ostream;
  25. class TimeRecord {
  26. double WallTime; ///< Wall clock time elapsed in seconds.
  27. double UserTime; ///< User time elapsed.
  28. double SystemTime; ///< System time elapsed.
  29. ssize_t MemUsed; ///< Memory allocated (in bytes).
  30. uint64_t InstructionsExecuted; ///< Number of instructions executed
  31. public:
  32. TimeRecord()
  33. : WallTime(0), UserTime(0), SystemTime(0), MemUsed(0),
  34. InstructionsExecuted(0) {}
  35. /// Get the current time and memory usage. If Start is true we get the memory
  36. /// usage before the time, otherwise we get time before memory usage. This
  37. /// matters if the time to get the memory usage is significant and shouldn't
  38. /// be counted as part of a duration.
  39. static TimeRecord getCurrentTime(bool Start = true);
  40. double getProcessTime() const { return UserTime + SystemTime; }
  41. double getUserTime() const { return UserTime; }
  42. double getSystemTime() const { return SystemTime; }
  43. double getWallTime() const { return WallTime; }
  44. ssize_t getMemUsed() const { return MemUsed; }
  45. uint64_t getInstructionsExecuted() const { return InstructionsExecuted; }
  46. bool operator<(const TimeRecord &T) const {
  47. // Sort by Wall Time elapsed, as it is the only thing really accurate
  48. return WallTime < T.WallTime;
  49. }
  50. void operator+=(const TimeRecord &RHS) {
  51. WallTime += RHS.WallTime;
  52. UserTime += RHS.UserTime;
  53. SystemTime += RHS.SystemTime;
  54. MemUsed += RHS.MemUsed;
  55. InstructionsExecuted += RHS.InstructionsExecuted;
  56. }
  57. void operator-=(const TimeRecord &RHS) {
  58. WallTime -= RHS.WallTime;
  59. UserTime -= RHS.UserTime;
  60. SystemTime -= RHS.SystemTime;
  61. MemUsed -= RHS.MemUsed;
  62. InstructionsExecuted -= RHS.InstructionsExecuted;
  63. }
  64. /// Print the current time record to \p OS, with a breakdown showing
  65. /// contributions to the \p Total time record.
  66. void print(const TimeRecord &Total, raw_ostream &OS) const;
  67. };
  68. /// This class is used to track the amount of time spent between invocations of
  69. /// its startTimer()/stopTimer() methods. Given appropriate OS support it can
  70. /// also keep track of the RSS of the program at various points. By default,
  71. /// the Timer will print the amount of time it has captured to standard error
  72. /// when the last timer is destroyed, otherwise it is printed when its
  73. /// TimerGroup is destroyed. Timers do not print their information if they are
  74. /// never started.
  75. class Timer {
  76. TimeRecord Time; ///< The total time captured.
  77. TimeRecord StartTime; ///< The time startTimer() was last called.
  78. std::string Name; ///< The name of this time variable.
  79. std::string Description; ///< Description of this time variable.
  80. bool Running = false; ///< Is the timer currently running?
  81. bool Triggered = false; ///< Has the timer ever been triggered?
  82. TimerGroup *TG = nullptr; ///< The TimerGroup this Timer is in.
  83. Timer **Prev = nullptr; ///< Pointer to \p Next of previous timer in group.
  84. Timer *Next = nullptr; ///< Next timer in the group.
  85. public:
  86. explicit Timer(StringRef TimerName, StringRef TimerDescription) {
  87. init(TimerName, TimerDescription);
  88. }
  89. Timer(StringRef TimerName, StringRef TimerDescription, TimerGroup &tg) {
  90. init(TimerName, TimerDescription, tg);
  91. }
  92. Timer(const Timer &RHS) {
  93. assert(!RHS.TG && "Can only copy uninitialized timers");
  94. }
  95. const Timer &operator=(const Timer &T) {
  96. assert(!TG && !T.TG && "Can only assign uninit timers");
  97. return *this;
  98. }
  99. ~Timer();
  100. /// Create an uninitialized timer, client must use 'init'.
  101. explicit Timer() = default;
  102. void init(StringRef TimerName, StringRef TimerDescription);
  103. void init(StringRef TimerName, StringRef TimerDescription, TimerGroup &tg);
  104. const std::string &getName() const { return Name; }
  105. const std::string &getDescription() const { return Description; }
  106. bool isInitialized() const { return TG != nullptr; }
  107. /// Check if the timer is currently running.
  108. bool isRunning() const { return Running; }
  109. /// Check if startTimer() has ever been called on this timer.
  110. bool hasTriggered() const { return Triggered; }
  111. /// Start the timer running. Time between calls to startTimer/stopTimer is
  112. /// counted by the Timer class. Note that these calls must be correctly
  113. /// paired.
  114. void startTimer();
  115. /// Stop the timer.
  116. void stopTimer();
  117. /// Clear the timer state.
  118. void clear();
  119. /// Return the duration for which this timer has been running.
  120. TimeRecord getTotalTime() const { return Time; }
  121. private:
  122. friend class TimerGroup;
  123. };
  124. /// The TimeRegion class is used as a helper class to call the startTimer() and
  125. /// stopTimer() methods of the Timer class. When the object is constructed, it
  126. /// starts the timer specified as its argument. When it is destroyed, it stops
  127. /// the relevant timer. This makes it easy to time a region of code.
  128. class TimeRegion {
  129. Timer *T;
  130. TimeRegion(const TimeRegion &) = delete;
  131. public:
  132. explicit TimeRegion(Timer &t) : T(&t) {
  133. T->startTimer();
  134. }
  135. explicit TimeRegion(Timer *t) : T(t) {
  136. if (T) T->startTimer();
  137. }
  138. ~TimeRegion() {
  139. if (T) T->stopTimer();
  140. }
  141. };
  142. /// This class is basically a combination of TimeRegion and Timer. It allows
  143. /// you to declare a new timer, AND specify the region to time, all in one
  144. /// statement. All timers with the same name are merged. This is primarily
  145. /// used for debugging and for hunting performance problems.
  146. struct NamedRegionTimer : public TimeRegion {
  147. explicit NamedRegionTimer(StringRef Name, StringRef Description,
  148. StringRef GroupName,
  149. StringRef GroupDescription, bool Enabled = true);
  150. };
  151. /// The TimerGroup class is used to group together related timers into a single
  152. /// report that is printed when the TimerGroup is destroyed. It is illegal to
  153. /// destroy a TimerGroup object before all of the Timers in it are gone. A
  154. /// TimerGroup can be specified for a newly created timer in its constructor.
  155. class TimerGroup {
  156. struct PrintRecord {
  157. TimeRecord Time;
  158. std::string Name;
  159. std::string Description;
  160. PrintRecord(const PrintRecord &Other) = default;
  161. PrintRecord &operator=(const PrintRecord &Other) = default;
  162. PrintRecord(const TimeRecord &Time, const std::string &Name,
  163. const std::string &Description)
  164. : Time(Time), Name(Name), Description(Description) {}
  165. bool operator <(const PrintRecord &Other) const {
  166. return Time < Other.Time;
  167. }
  168. };
  169. std::string Name;
  170. std::string Description;
  171. Timer *FirstTimer = nullptr; ///< First timer in the group.
  172. std::vector<PrintRecord> TimersToPrint;
  173. TimerGroup **Prev; ///< Pointer to Next field of previous timergroup in list.
  174. TimerGroup *Next; ///< Pointer to next timergroup in list.
  175. TimerGroup(const TimerGroup &TG) = delete;
  176. void operator=(const TimerGroup &TG) = delete;
  177. public:
  178. explicit TimerGroup(StringRef Name, StringRef Description);
  179. explicit TimerGroup(StringRef Name, StringRef Description,
  180. const StringMap<TimeRecord> &Records);
  181. ~TimerGroup();
  182. void setName(StringRef NewName, StringRef NewDescription) {
  183. Name.assign(NewName.begin(), NewName.end());
  184. Description.assign(NewDescription.begin(), NewDescription.end());
  185. }
  186. /// Print any started timers in this group, optionally resetting timers after
  187. /// printing them.
  188. void print(raw_ostream &OS, bool ResetAfterPrint = false);
  189. /// Clear all timers in this group.
  190. void clear();
  191. /// This static method prints all timers.
  192. static void printAll(raw_ostream &OS);
  193. /// Clear out all timers. This is mostly used to disable automatic
  194. /// printing on shutdown, when timers have already been printed explicitly
  195. /// using \c printAll or \c printJSONValues.
  196. static void clearAll();
  197. const char *printJSONValues(raw_ostream &OS, const char *delim);
  198. /// Prints all timers as JSON key/value pairs.
  199. static const char *printAllJSONValues(raw_ostream &OS, const char *delim);
  200. /// Ensure global timer group lists are initialized. This function is mostly
  201. /// used by the Statistic code to influence the construction and destruction
  202. /// order of the global timer lists.
  203. static void ConstructTimerLists();
  204. /// This makes the default group unmanaged, and lets the user manage the
  205. /// group's lifetime.
  206. static std::unique_ptr<TimerGroup> aquireDefaultGroup();
  207. private:
  208. friend class Timer;
  209. friend void PrintStatisticsJSON(raw_ostream &OS);
  210. void addTimer(Timer &T);
  211. void removeTimer(Timer &T);
  212. void prepareToPrintList(bool reset_time = false);
  213. void PrintQueuedTimers(raw_ostream &OS);
  214. void printJSONValue(raw_ostream &OS, const PrintRecord &R,
  215. const char *suffix, double Value);
  216. };
  217. } // end namespace llvm
  218. #endif
  219. #ifdef __GNUC__
  220. #pragma GCC diagnostic pop
  221. #endif