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