1 //===-- Timer.cpp - Interval Timing Support -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file Interval Timing implementation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Support/Timer.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/Mutex.h"
22 #include "llvm/Support/Process.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Support/YAMLTraits.h"
25 using namespace llvm;
26 
27 // This ugly hack is brought to you courtesy of constructor/destructor ordering
28 // being unspecified by C++.  Basically the problem is that a Statistic object
29 // gets destroyed, which ends up calling 'GetLibSupportInfoOutputFile()'
30 // (below), which calls this function.  LibSupportInfoOutputFilename used to be
31 // a global variable, but sometimes it would get destroyed before the Statistic,
32 // causing havoc to ensue.  We "fix" this by creating the string the first time
33 // it is needed and never destroying it.
34 static ManagedStatic<std::string> LibSupportInfoOutputFilename;
35 static std::string &getLibSupportInfoOutputFilename() {
36   return *LibSupportInfoOutputFilename;
37 }
38 
39 static ManagedStatic<sys::SmartMutex<true> > TimerLock;
40 
41 namespace {
42   static cl::opt<bool>
43   TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
44                                       "tracking (this may be slow)"),
45              cl::Hidden);
46 
47   static cl::opt<std::string, true>
48   InfoOutputFilename("info-output-file", cl::value_desc("filename"),
49                      cl::desc("File to append -stats and -timer output to"),
50                    cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
51 }
52 
53 std::unique_ptr<raw_fd_ostream> llvm::CreateInfoOutputFile() {
54   const std::string &OutputFilename = getLibSupportInfoOutputFilename();
55   if (OutputFilename.empty())
56     return llvm::make_unique<raw_fd_ostream>(2, false); // stderr.
57   if (OutputFilename == "-")
58     return llvm::make_unique<raw_fd_ostream>(1, false); // stdout.
59 
60   // Append mode is used because the info output file is opened and closed
61   // each time -stats or -time-passes wants to print output to it. To
62   // compensate for this, the test-suite Makefiles have code to delete the
63   // info output file before running commands which write to it.
64   std::error_code EC;
65   auto Result = llvm::make_unique<raw_fd_ostream>(
66       OutputFilename, EC, sys::fs::F_Append | sys::fs::F_Text);
67   if (!EC)
68     return Result;
69 
70   errs() << "Error opening info-output-file '"
71     << OutputFilename << " for appending!\n";
72   return llvm::make_unique<raw_fd_ostream>(2, false); // stderr.
73 }
74 
75 static TimerGroup *getDefaultTimerGroup() {
76   static TimerGroup DefaultTimerGroup("misc", "Miscellaneous Ungrouped Timers");
77   return &DefaultTimerGroup;
78 }
79 
80 //===----------------------------------------------------------------------===//
81 // Timer Implementation
82 //===----------------------------------------------------------------------===//
83 
84 void Timer::init(StringRef Name, StringRef Description) {
85   init(Name, Description, *getDefaultTimerGroup());
86 }
87 
88 void Timer::init(StringRef Name, StringRef Description, TimerGroup &tg) {
89   assert(!TG && "Timer already initialized");
90   this->Name.assign(Name.begin(), Name.end());
91   this->Description.assign(Description.begin(), Description.end());
92   Running = Triggered = false;
93   TG = &tg;
94   TG->addTimer(*this);
95 }
96 
97 Timer::~Timer() {
98   if (!TG) return;  // Never initialized, or already cleared.
99   TG->removeTimer(*this);
100 }
101 
102 static inline size_t getMemUsage() {
103   if (!TrackSpace) return 0;
104   return sys::Process::GetMallocUsage();
105 }
106 
107 TimeRecord TimeRecord::getCurrentTime(bool Start) {
108   using Seconds = std::chrono::duration<double, std::ratio<1>>;
109   TimeRecord Result;
110   sys::TimePoint<> now;
111   std::chrono::nanoseconds user, sys;
112 
113   if (Start) {
114     Result.MemUsed = getMemUsage();
115     sys::Process::GetTimeUsage(now, user, sys);
116   } else {
117     sys::Process::GetTimeUsage(now, user, sys);
118     Result.MemUsed = getMemUsage();
119   }
120 
121   Result.WallTime = Seconds(now.time_since_epoch()).count();
122   Result.UserTime = Seconds(user).count();
123   Result.SystemTime = Seconds(sys).count();
124   return Result;
125 }
126 
127 void Timer::startTimer() {
128   assert(!Running && "Cannot start a running timer");
129   Running = Triggered = true;
130   StartTime = TimeRecord::getCurrentTime(true);
131 }
132 
133 void Timer::stopTimer() {
134   assert(Running && "Cannot stop a paused timer");
135   Running = false;
136   Time += TimeRecord::getCurrentTime(false);
137   Time -= StartTime;
138 }
139 
140 void Timer::clear() {
141   Running = Triggered = false;
142   Time = StartTime = TimeRecord();
143 }
144 
145 static void printVal(double Val, double Total, raw_ostream &OS) {
146   if (Total < 1e-7)   // Avoid dividing by zero.
147     OS << "        -----     ";
148   else
149     OS << format("  %7.4f (%5.1f%%)", Val, Val*100/Total);
150 }
151 
152 void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const {
153   if (Total.getUserTime())
154     printVal(getUserTime(), Total.getUserTime(), OS);
155   if (Total.getSystemTime())
156     printVal(getSystemTime(), Total.getSystemTime(), OS);
157   if (Total.getProcessTime())
158     printVal(getProcessTime(), Total.getProcessTime(), OS);
159   printVal(getWallTime(), Total.getWallTime(), OS);
160 
161   OS << "  ";
162 
163   if (Total.getMemUsed())
164     OS << format("%9" PRId64 "  ", (int64_t)getMemUsed());
165 }
166 
167 
168 //===----------------------------------------------------------------------===//
169 //   NamedRegionTimer Implementation
170 //===----------------------------------------------------------------------===//
171 
172 namespace {
173 
174 typedef StringMap<Timer> Name2TimerMap;
175 
176 class Name2PairMap {
177   StringMap<std::pair<TimerGroup*, Name2TimerMap> > Map;
178 public:
179   ~Name2PairMap() {
180     for (StringMap<std::pair<TimerGroup*, Name2TimerMap> >::iterator
181          I = Map.begin(), E = Map.end(); I != E; ++I)
182       delete I->second.first;
183   }
184 
185   Timer &get(StringRef Name, StringRef Description, StringRef GroupName,
186              StringRef GroupDescription) {
187     sys::SmartScopedLock<true> L(*TimerLock);
188 
189     std::pair<TimerGroup*, Name2TimerMap> &GroupEntry = Map[GroupName];
190 
191     if (!GroupEntry.first)
192       GroupEntry.first = new TimerGroup(GroupName, GroupDescription);
193 
194     Timer &T = GroupEntry.second[Name];
195     if (!T.isInitialized())
196       T.init(Name, Description, *GroupEntry.first);
197     return T;
198   }
199 };
200 
201 }
202 
203 static ManagedStatic<Name2PairMap> NamedGroupedTimers;
204 
205 NamedRegionTimer::NamedRegionTimer(StringRef Name, StringRef Description,
206                                    StringRef GroupName,
207                                    StringRef GroupDescription, bool Enabled)
208   : TimeRegion(!Enabled ? nullptr
209                  : &NamedGroupedTimers->get(Name, Description, GroupName,
210                                             GroupDescription)) {}
211 
212 //===----------------------------------------------------------------------===//
213 //   TimerGroup Implementation
214 //===----------------------------------------------------------------------===//
215 
216 /// This is the global list of TimerGroups, maintained by the TimerGroup
217 /// ctor/dtor and is protected by the TimerLock lock.
218 static TimerGroup *TimerGroupList = nullptr;
219 
220 TimerGroup::TimerGroup(StringRef Name, StringRef Description)
221   : Name(Name.begin(), Name.end()),
222     Description(Description.begin(), Description.end()) {
223   // Add the group to TimerGroupList.
224   sys::SmartScopedLock<true> L(*TimerLock);
225   if (TimerGroupList)
226     TimerGroupList->Prev = &Next;
227   Next = TimerGroupList;
228   Prev = &TimerGroupList;
229   TimerGroupList = this;
230 }
231 
232 TimerGroup::~TimerGroup() {
233   // If the timer group is destroyed before the timers it owns, accumulate and
234   // print the timing data.
235   while (FirstTimer)
236     removeTimer(*FirstTimer);
237 
238   // Remove the group from the TimerGroupList.
239   sys::SmartScopedLock<true> L(*TimerLock);
240   *Prev = Next;
241   if (Next)
242     Next->Prev = Prev;
243 }
244 
245 
246 void TimerGroup::removeTimer(Timer &T) {
247   sys::SmartScopedLock<true> L(*TimerLock);
248 
249   // If the timer was started, move its data to TimersToPrint.
250   if (T.hasTriggered())
251     TimersToPrint.emplace_back(T.Time, T.Name, T.Description);
252 
253   T.TG = nullptr;
254 
255   // Unlink the timer from our list.
256   *T.Prev = T.Next;
257   if (T.Next)
258     T.Next->Prev = T.Prev;
259 
260   // Print the report when all timers in this group are destroyed if some of
261   // them were started.
262   if (FirstTimer || TimersToPrint.empty())
263     return;
264 
265   std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
266   PrintQueuedTimers(*OutStream);
267 }
268 
269 void TimerGroup::addTimer(Timer &T) {
270   sys::SmartScopedLock<true> L(*TimerLock);
271 
272   // Add the timer to our list.
273   if (FirstTimer)
274     FirstTimer->Prev = &T.Next;
275   T.Next = FirstTimer;
276   T.Prev = &FirstTimer;
277   FirstTimer = &T;
278 }
279 
280 void TimerGroup::PrintQueuedTimers(raw_ostream &OS) {
281   // Sort the timers in descending order by amount of time taken.
282   std::sort(TimersToPrint.begin(), TimersToPrint.end());
283 
284   TimeRecord Total;
285   for (const PrintRecord &Record : TimersToPrint)
286     Total += Record.Time;
287 
288   // Print out timing header.
289   OS << "===" << std::string(73, '-') << "===\n";
290   // Figure out how many spaces to indent TimerGroup name.
291   unsigned Padding = (80-Description.length())/2;
292   if (Padding > 80) Padding = 0;         // Don't allow "negative" numbers
293   OS.indent(Padding) << Description << '\n';
294   OS << "===" << std::string(73, '-') << "===\n";
295 
296   // If this is not an collection of ungrouped times, print the total time.
297   // Ungrouped timers don't really make sense to add up.  We still print the
298   // TOTAL line to make the percentages make sense.
299   if (this != getDefaultTimerGroup())
300     OS << format("  Total Execution Time: %5.4f seconds (%5.4f wall clock)\n",
301                  Total.getProcessTime(), Total.getWallTime());
302   OS << '\n';
303 
304   if (Total.getUserTime())
305     OS << "   ---User Time---";
306   if (Total.getSystemTime())
307     OS << "   --System Time--";
308   if (Total.getProcessTime())
309     OS << "   --User+System--";
310   OS << "   ---Wall Time---";
311   if (Total.getMemUsed())
312     OS << "  ---Mem---";
313   OS << "  --- Name ---\n";
314 
315   // Loop through all of the timing data, printing it out.
316   for (const PrintRecord &Record : make_range(TimersToPrint.rbegin(),
317                                               TimersToPrint.rend())) {
318     Record.Time.print(Total, OS);
319     OS << Record.Description << '\n';
320   }
321 
322   Total.print(Total, OS);
323   OS << "Total\n\n";
324   OS.flush();
325 
326   TimersToPrint.clear();
327 }
328 
329 void TimerGroup::prepareToPrintList() {
330   // See if any of our timers were started, if so add them to TimersToPrint and
331   // reset them.
332   for (Timer *T = FirstTimer; T; T = T->Next) {
333     if (!T->hasTriggered()) continue;
334     TimersToPrint.emplace_back(T->Time, T->Name, T->Description);
335 
336     // Clear out the time.
337     T->clear();
338   }
339 }
340 
341 void TimerGroup::print(raw_ostream &OS) {
342   sys::SmartScopedLock<true> L(*TimerLock);
343 
344   prepareToPrintList();
345 
346   // If any timers were started, print the group.
347   if (!TimersToPrint.empty())
348     PrintQueuedTimers(OS);
349 }
350 
351 void TimerGroup::printAll(raw_ostream &OS) {
352   sys::SmartScopedLock<true> L(*TimerLock);
353 
354   for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
355     TG->print(OS);
356 }
357 
358 void TimerGroup::printJSONValue(raw_ostream &OS, const PrintRecord &R,
359                                 const char *suffix, double Value) {
360   assert(!yaml::needsQuotes(Name) && "TimerGroup name needs no quotes");
361   assert(!yaml::needsQuotes(R.Name) && "Timer name needs no quotes");
362   OS << "\t\"time." << Name << '.' << R.Name << suffix << "\": " << Value;
363 }
364 
365 const char *TimerGroup::printJSONValues(raw_ostream &OS, const char *delim) {
366   prepareToPrintList();
367   for (const PrintRecord &R : TimersToPrint) {
368     OS << delim;
369     delim = ",\n";
370 
371     const TimeRecord &T = R.Time;
372     printJSONValue(OS, R, ".wall", T.getWallTime());
373     OS << delim;
374     printJSONValue(OS, R, ".user", T.getUserTime());
375     OS << delim;
376     printJSONValue(OS, R, ".sys", T.getSystemTime());
377   }
378   TimersToPrint.clear();
379   return delim;
380 }
381 
382 const char *TimerGroup::printAllJSONValues(raw_ostream &OS, const char *delim) {
383   sys::SmartScopedLock<true> L(*TimerLock);
384   for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
385     delim = TG->printJSONValues(OS, delim);
386   return delim;
387 }
388 
389 void TimerGroup::ConstructTimerLists() {
390   (void)*NamedGroupedTimers;
391 }
392