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