LLVM 22.0.0git
Timer.h
Go to the documentation of this file.
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"
16#include "llvm/Support/Mutex.h"
17#include <cassert>
18#include <string>
19#include <vector>
20
21namespace llvm {
22
23class TimerGlobals;
24class TimerGroup;
25class raw_ostream;
26
28 double WallTime = 0.0; ///< Wall clock time elapsed in seconds.
29 double UserTime = 0.0; ///< User time elapsed.
30 double SystemTime = 0.0; ///< System time elapsed.
31 ssize_t MemUsed = 0; ///< Memory allocated (in bytes).
32 uint64_t InstructionsExecuted = 0; ///< Number of instructions executed
33public:
34 TimeRecord() = default;
35
36 /// Get the current time and memory usage. If Start is true we get the memory
37 /// usage before the time, otherwise we get time before memory usage. This
38 /// matters if the time to get the memory usage is significant and shouldn't
39 /// be counted as part of a duration.
40 LLVM_ABI static TimeRecord getCurrentTime(bool Start = true);
41
42 double getProcessTime() const { return UserTime + SystemTime; }
43 double getUserTime() const { return UserTime; }
44 double getSystemTime() const { return SystemTime; }
45 double getWallTime() const { return WallTime; }
46 ssize_t getMemUsed() const { return MemUsed; }
47 uint64_t getInstructionsExecuted() const { return InstructionsExecuted; }
48
49 bool operator<(const TimeRecord &T) const {
50 // Sort by Wall Time elapsed, as it is the only thing really accurate
51 return WallTime < T.WallTime;
52 }
53
54 void operator+=(const TimeRecord &RHS) {
55 WallTime += RHS.WallTime;
56 UserTime += RHS.UserTime;
57 SystemTime += RHS.SystemTime;
58 MemUsed += RHS.MemUsed;
59 InstructionsExecuted += RHS.InstructionsExecuted;
60 }
61 void operator-=(const TimeRecord &RHS) {
62 WallTime -= RHS.WallTime;
63 UserTime -= RHS.UserTime;
64 SystemTime -= RHS.SystemTime;
65 MemUsed -= RHS.MemUsed;
66 InstructionsExecuted -= RHS.InstructionsExecuted;
67 }
69 TimeRecord R = *this;
70 R -= RHS;
71 return R;
72 }
73 // Feel free to add operator+ if you need it
74
75 /// Print the current time record to \p OS, with a breakdown showing
76 /// contributions to the \p Total time record.
77 LLVM_ABI void print(const TimeRecord &Total, raw_ostream &OS) const;
78};
79
80/// This class is used to track the amount of time spent between invocations of
81/// its startTimer()/stopTimer() methods. Given appropriate OS support it can
82/// also keep track of the RSS of the program at various points. By default,
83/// the Timer will print the amount of time it has captured to standard error
84/// when the last timer is destroyed, otherwise it is printed when its
85/// TimerGroup is destroyed. Timers do not print their information if they are
86/// never started.
87class Timer {
88 TimeRecord Time; ///< The total time captured.
89 TimeRecord StartTime; ///< The time startTimer() was last called.
90 std::string Name; ///< The name of this time variable.
91 std::string Description; ///< Description of this time variable.
92 bool Running = false; ///< Is the timer currently running?
93 bool Triggered = false; ///< Has the timer ever been triggered?
94 TimerGroup *TG = nullptr; ///< The TimerGroup this Timer is in.
95
96 Timer **Prev = nullptr; ///< Pointer to \p Next of previous timer in group.
97 Timer *Next = nullptr; ///< Next timer in the group.
98public:
99 explicit Timer(StringRef TimerName, StringRef TimerDescription) {
100 init(TimerName, TimerDescription);
101 }
102 Timer(StringRef TimerName, StringRef TimerDescription, TimerGroup &tg) {
103 init(TimerName, TimerDescription, tg);
104 }
105 Timer(const Timer &RHS) {
106 assert(!RHS.TG && "Can only copy uninitialized timers");
107 }
108 const Timer &operator=(const Timer &T) {
109 assert(!TG && !T.TG && "Can only assign uninit timers");
110 return *this;
111 }
113
114 /// Create an uninitialized timer, client must use 'init'.
115 explicit Timer() = default;
116 LLVM_ABI void init(StringRef TimerName, StringRef TimerDescription);
117 LLVM_ABI void init(StringRef TimerName, StringRef TimerDescription,
118 TimerGroup &tg);
119
120 const std::string &getName() const { return Name; }
121 const std::string &getDescription() const { return Description; }
122 bool isInitialized() const { return TG != nullptr; }
123
124 /// Check if the timer is currently running.
125 bool isRunning() const { return Running; }
126
127 /// Check if startTimer() has ever been called on this timer.
128 bool hasTriggered() const { return Triggered; }
129
130 /// Start the timer running. Time between calls to startTimer/stopTimer is
131 /// counted by the Timer class. Note that these calls must be correctly
132 /// paired.
133 LLVM_ABI void startTimer();
134
135 /// Stop the timer.
136 LLVM_ABI void stopTimer();
137
138 /// Clear the timer state.
139 LLVM_ABI void clear();
140
141 /// Stop the timer and start another timer.
142 LLVM_ABI void yieldTo(Timer &);
143
144 /// Return the duration for which this timer has been running.
145 TimeRecord getTotalTime() const { return Time; }
146
147private:
148 friend class TimerGroup;
149};
150
151/// The TimeRegion class is used as a helper class to call the startTimer() and
152/// stopTimer() methods of the Timer class. When the object is constructed, it
153/// starts the timer specified as its argument. When it is destroyed, it stops
154/// the relevant timer. This makes it easy to time a region of code.
155class TimeRegion {
156 Timer *T;
157 TimeRegion(const TimeRegion &) = delete;
158
159public:
160 explicit TimeRegion(Timer &t) : T(&t) {
161 T->startTimer();
162 }
163 explicit TimeRegion(Timer *t) : T(t) {
164 if (T) T->startTimer();
165 }
167 if (T) T->stopTimer();
168 }
169};
170
171/// This class is basically a combination of TimeRegion and Timer. It allows
172/// you to declare a new timer, AND specify the region to time, all in one
173/// statement. All timers with the same name are merged. This is primarily
174/// used for debugging and for hunting performance problems.
175struct NamedRegionTimer : TimeRegion {
176 LLVM_ABI explicit NamedRegionTimer(StringRef Name, StringRef Description,
177 StringRef GroupName,
178 StringRef GroupDescription,
179 bool Enabled = true);
180
181 // Create or get a TimerGroup stored in the same global map owned by
182 // NamedRegionTimer.
184 StringRef GroupDescription);
185};
186
187/// The TimerGroup class is used to group together related timers into a single
188/// report that is printed when the TimerGroup is destroyed. It is illegal to
189/// destroy a TimerGroup object before all of the Timers in it are gone. A
190/// TimerGroup can be specified for a newly created timer in its constructor.
191class TimerGroup {
192 struct PrintRecord {
193 TimeRecord Time;
194 std::string Name;
195 std::string Description;
196
197 PrintRecord(const PrintRecord &Other) = default;
198 PrintRecord &operator=(const PrintRecord &Other) = default;
199 PrintRecord(const TimeRecord &Time, const std::string &Name,
200 const std::string &Description)
201 : Time(Time), Name(Name), Description(Description) {}
202
203 bool operator <(const PrintRecord &Other) const {
204 return Time < Other.Time;
205 }
206 };
207 std::string Name;
208 std::string Description;
209 Timer *FirstTimer = nullptr; ///< First timer in the group.
210 std::vector<PrintRecord> TimersToPrint;
211 bool PrintOnExit;
212
213 TimerGroup **Prev; ///< Pointer to Next field of previous timergroup in list.
214 TimerGroup *Next; ///< Pointer to next timergroup in list.
215 TimerGroup(const TimerGroup &TG) = delete;
216 void operator=(const TimerGroup &TG) = delete;
217
218 friend class TimerGlobals;
219 explicit TimerGroup(StringRef Name, StringRef Description,
220 sys::SmartMutex<true> &lock, bool PrintOnExit);
221
222public:
223 LLVM_ABI explicit TimerGroup(StringRef Name, StringRef Description,
224 bool PrintOnExit = true);
225
226 LLVM_ABI explicit TimerGroup(StringRef Name, StringRef Description,
227 const StringMap<TimeRecord> &Records,
228 bool PrintOnExit = true);
229
231
232 void setName(StringRef NewName, StringRef NewDescription) {
233 Name.assign(NewName.begin(), NewName.end());
234 Description.assign(NewDescription.begin(), NewDescription.end());
235 }
236
237 /// Print any started timers in this group, optionally resetting timers after
238 /// printing them.
239 LLVM_ABI void print(raw_ostream &OS, bool ResetAfterPrint = false);
240
241 /// Clear all timers in this group.
242 LLVM_ABI void clear();
243
244 /// This static method prints all timers.
245 LLVM_ABI static void printAll(raw_ostream &OS);
246
247 /// Clear out all timers. This is mostly used to disable automatic
248 /// printing on shutdown, when timers have already been printed explicitly
249 /// using \c printAll or \c printJSONValues.
250 LLVM_ABI static void clearAll();
251
252 LLVM_ABI const char *printJSONValues(raw_ostream &OS, const char *delim);
253
254 /// Prints all timers as JSON key/value pairs.
255 LLVM_ABI static const char *printAllJSONValues(raw_ostream &OS,
256 const char *delim);
257
258 /// Ensure global objects required for statistics printing are initialized.
259 /// This function is used by the Statistic code to ensure correct order of
260 /// global constructors and destructors.
261 LLVM_ABI static void constructForStatistics();
262
263 /// This makes the timer globals unmanaged, and lets the user manage the
264 /// lifetime.
265 LLVM_ABI static void *acquireTimerGlobals();
266
267private:
268 friend class Timer;
270 void addTimer(Timer &T);
271 void removeTimer(Timer &T);
272 void prepareToPrintList(bool reset_time = false);
273 void PrintQueuedTimers(raw_ostream &OS);
274 void printJSONValue(raw_ostream &OS, const PrintRecord &R,
275 const char *suffix, double Value);
276};
277
278} // end namespace llvm
279
280#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
#define LLVM_ABI
Definition Compiler.h:213
#define T
Value * RHS
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
iterator begin() const
Definition StringRef.h:112
iterator end() const
Definition StringRef.h:114
double getUserTime() const
Definition Timer.h:43
double getProcessTime() const
Definition Timer.h:42
TimeRecord()=default
static LLVM_ABI TimeRecord getCurrentTime(bool Start=true)
Get the current time and memory usage.
Definition Timer.cpp:128
double getWallTime() const
Definition Timer.h:45
TimeRecord operator-(const TimeRecord &RHS) const
Definition Timer.h:68
ssize_t getMemUsed() const
Definition Timer.h:46
void operator-=(const TimeRecord &RHS)
Definition Timer.h:61
void operator+=(const TimeRecord &RHS)
Definition Timer.h:54
double getSystemTime() const
Definition Timer.h:44
bool operator<(const TimeRecord &T) const
Definition Timer.h:49
LLVM_ABI void print(const TimeRecord &Total, raw_ostream &OS) const
Print the current time record to OS, with a breakdown showing contributions to the Total time record.
Definition Timer.cpp:186
uint64_t getInstructionsExecuted() const
Definition Timer.h:47
TimeRegion(Timer &t)
Definition Timer.h:160
TimeRegion(Timer *t)
Definition Timer.h:163
The TimerGroup class is used to group together related timers into a single report that is printed wh...
Definition Timer.h:191
static LLVM_ABI void printAll(raw_ostream &OS)
This static method prints all timers.
Definition Timer.cpp:444
void setName(StringRef NewName, StringRef NewDescription)
Definition Timer.h:232
LLVM_ABI void print(raw_ostream &OS, bool ResetAfterPrint=false)
Print any started timers in this group, optionally resetting timers after printing them.
Definition Timer.cpp:426
friend class Timer
Definition Timer.h:268
static LLVM_ABI void clearAll()
Clear out all timers.
Definition Timer.cpp:451
LLVM_ABI void clear()
Clear all timers in this group.
Definition Timer.cpp:438
LLVM_ABI friend void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
friend class TimerGlobals
Definition Timer.h:218
LLVM_ABI ~TimerGroup()
Definition Timer.cpp:300
static LLVM_ABI void * acquireTimerGlobals()
This makes the timer globals unmanaged, and lets the user manage the lifetime.
Definition Timer.cpp:574
static LLVM_ABI const char * printAllJSONValues(raw_ostream &OS, const char *delim)
Prints all timers as JSON key/value pairs.
Definition Timer.cpp:491
LLVM_ABI const char * printJSONValues(raw_ostream &OS, const char *delim)
Definition Timer.cpp:464
static LLVM_ABI void constructForStatistics()
Ensure global objects required for statistics printing are initialized.
Definition Timer.cpp:570
This class is used to track the amount of time spent between invocations of its startTimer()/stopTime...
Definition Timer.h:87
bool hasTriggered() const
Check if startTimer() has ever been called on this timer.
Definition Timer.h:128
LLVM_ABI void yieldTo(Timer &)
Stop the timer and start another timer.
Definition Timer.cpp:174
LLVM_ABI ~Timer()
Definition Timer.cpp:106
bool isRunning() const
Check if the timer is currently running.
Definition Timer.h:125
LLVM_ABI void stopTimer()
Stop the timer.
Definition Timer.cpp:159
const Timer & operator=(const Timer &T)
Definition Timer.h:108
const std::string & getDescription() const
Definition Timer.h:121
LLVM_ABI void init(StringRef TimerName, StringRef TimerDescription)
Definition Timer.cpp:92
LLVM_ABI void clear()
Clear the timer state.
Definition Timer.cpp:169
friend class TimerGroup
Definition Timer.h:148
const std::string & getName() const
Definition Timer.h:120
Timer()=default
Create an uninitialized timer, client must use 'init'.
Timer(const Timer &RHS)
Definition Timer.h:105
bool isInitialized() const
Definition Timer.h:122
Timer(StringRef TimerName, StringRef TimerDescription)
Definition Timer.h:99
Timer(StringRef TimerName, StringRef TimerDescription, TimerGroup &tg)
Definition Timer.h:102
LLVM_ABI void startTimer()
Start the timer running.
Definition Timer.cpp:150
TimeRecord getTotalTime() const
Return the duration for which this timer has been running.
Definition Timer.h:145
LLVM Value Representation.
Definition Value.h:75
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
SmartMutex - A mutex with a compile time constant parameter that indicates whether this mutex should ...
Definition Mutex.h:28
This is an optimization pass for GlobalISel generic memory operations.
@ Other
Any other memory.
Definition ModRef.h:68
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:27
LLVM_ABI NamedRegionTimer(StringRef Name, StringRef Description, StringRef GroupName, StringRef GroupDescription, bool Enabled=true)
Definition Timer.cpp:252
static LLVM_ABI TimerGroup & getNamedTimerGroup(StringRef GroupName, StringRef GroupDescription)
Definition Timer.cpp:260