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