reapply my timer rewrite with a change for PassManager to store
[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/StringMap.h"
23 #include <map>
24 using namespace llvm;
25
26 // GetLibSupportInfoOutputFile - Return a file stream to print our output on.
27 namespace llvm { extern raw_ostream *GetLibSupportInfoOutputFile(); }
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 // GetLibSupportInfoOutputFile - Return a file stream to print our output on.
57 raw_ostream *llvm::GetLibSupportInfoOutputFile() {
58   std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
59   if (LibSupportInfoOutputFilename.empty())
60     return &errs();
61   if (LibSupportInfoOutputFilename == "-")
62     return &outs();
63   
64   std::string Error;
65   raw_ostream *Result = new raw_fd_ostream(LibSupportInfoOutputFilename.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     << LibSupportInfoOutputFilename << " for appending!\n";
72   delete Result;
73   return &errs();
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(const std::string &N) {
100   assert(TG == 0 && "Timer already initialized");
101   Name = N;
102   Started = false;
103   TG = getDefaultTimerGroup();
104   TG->addTimer();
105 }
106
107 void Timer::init(const std::string &N, TimerGroup &tg) {
108   assert(TG == 0 && "Timer already initialized");
109   Name = N;
110   Started = false;
111   TG = &tg;
112   TG->addTimer();
113 }
114
115 Timer::~Timer() {
116   if (!TG) return;  // Never initialized.
117   
118   if (Started) {
119     Started = false;
120     TG->addTimerToPrint(Time, Name);
121   }
122   TG->removeTimer();
123 }
124
125 static inline size_t getMemUsage() {
126   if (TrackSpace)
127     return sys::Process::GetMallocUsage();
128   return 0;
129 }
130
131 TimeRecord TimeRecord::getCurrentTime(bool Start) {
132   TimeRecord Result;
133
134   sys::TimeValue now(0,0);
135   sys::TimeValue user(0,0);
136   sys::TimeValue sys(0,0);
137
138   ssize_t MemUsed = 0;
139   if (Start) {
140     MemUsed = getMemUsage();
141     sys::Process::GetTimeUsage(now, user, sys);
142   } else {
143     sys::Process::GetTimeUsage(now, user, sys);
144     MemUsed = getMemUsage();
145   }
146
147   Result.WallTime   =  now.seconds() +  now.microseconds() / 1000000.0;
148   Result.UserTime   = user.seconds() + user.microseconds() / 1000000.0;
149   Result.SystemTime =  sys.seconds() +  sys.microseconds() / 1000000.0;
150   Result.MemUsed = MemUsed;
151   return Result;
152 }
153
154 static ManagedStatic<std::vector<Timer*> > ActiveTimers;
155
156 void Timer::startTimer() {
157   Started = true;
158   ActiveTimers->push_back(this);
159   Time -= TimeRecord::getCurrentTime(true);
160 }
161
162 void Timer::stopTimer() {
163   Time += TimeRecord::getCurrentTime(false);
164
165   if (ActiveTimers->back() == this) {
166     ActiveTimers->pop_back();
167   } else {
168     std::vector<Timer*>::iterator I =
169       std::find(ActiveTimers->begin(), ActiveTimers->end(), this);
170     assert(I != ActiveTimers->end() && "stop but no startTimer?");
171     ActiveTimers->erase(I);
172   }
173 }
174
175 static void printVal(double Val, double Total, raw_ostream &OS) {
176   if (Total < 1e-7)   // Avoid dividing by zero.
177     OS << "        -----     ";
178   else {
179     OS << "  " << format("%7.4f", Val) << " (";
180     OS << format("%5.1f", Val*100/Total) << "%)";
181   }
182 }
183
184 void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const {
185   if (Total.getUserTime())
186     printVal(getUserTime(), Total.getUserTime(), OS);
187   if (Total.getSystemTime())
188     printVal(getSystemTime(), Total.getSystemTime(), OS);
189   if (Total.getProcessTime())
190     printVal(getProcessTime(), Total.getProcessTime(), OS);
191   printVal(getWallTime(), Total.getWallTime(), OS);
192   
193   OS << "  ";
194   
195   if (Total.getMemUsed())
196     OS << format("%9lld", (long long)getMemUsed()) << "  ";
197 }
198
199
200 //===----------------------------------------------------------------------===//
201 //   NamedRegionTimer Implementation
202 //===----------------------------------------------------------------------===//
203
204 typedef StringMap<Timer> Name2TimerMap;
205 typedef StringMap<std::pair<TimerGroup, Name2TimerMap> > Name2PairMap;
206
207 static ManagedStatic<Name2TimerMap> NamedTimers;
208 static ManagedStatic<Name2PairMap> NamedGroupedTimers;
209
210 static Timer &getNamedRegionTimer(const std::string &Name) {
211   sys::SmartScopedLock<true> L(*TimerLock);
212   
213   Timer &T = (*NamedTimers)[Name];
214   if (!T.isInitialized())
215     T.init(Name);
216   return T;
217 }
218
219 static Timer &getNamedRegionTimer(const std::string &Name,
220                                   const std::string &GroupName) {
221   sys::SmartScopedLock<true> L(*TimerLock);
222
223   std::pair<TimerGroup, Name2TimerMap> &GroupEntry =
224     (*NamedGroupedTimers)[GroupName];
225
226   if (GroupEntry.second.empty())
227     GroupEntry.first.setName(GroupName);
228
229   Timer &T = GroupEntry.second[Name];
230   if (!T.isInitialized())
231     T.init(Name);
232   return T;
233 }
234
235 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
236   : TimeRegion(getNamedRegionTimer(Name)) {}
237
238 NamedRegionTimer::NamedRegionTimer(const std::string &Name,
239                                    const std::string &GroupName)
240   : TimeRegion(getNamedRegionTimer(Name, GroupName)) {}
241
242 //===----------------------------------------------------------------------===//
243 //   TimerGroup Implementation
244 //===----------------------------------------------------------------------===//
245
246 void TimerGroup::removeTimer() {
247   sys::SmartScopedLock<true> L(*TimerLock);
248   if (--NumTimers != 0 || TimersToPrint.empty())
249     return; // Don't print timing report.
250   
251   // Sort the timers in descending order by amount of time taken.
252   std::sort(TimersToPrint.begin(), TimersToPrint.end());
253
254   // Figure out how many spaces to indent TimerGroup name.
255   unsigned Padding = (80-Name.length())/2;
256   if (Padding > 80) Padding = 0;         // Don't allow "negative" numbers
257
258   raw_ostream *OutStream = GetLibSupportInfoOutputFile();
259
260   TimeRecord Total;
261   for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
262     Total += TimersToPrint[i].first;
263
264   // Print out timing header.
265   *OutStream << "===" << std::string(73, '-') << "===\n";
266   OutStream->indent(Padding) << Name << '\n';
267   *OutStream << "===" << std::string(73, '-') << "===\n";
268
269   // If this is not an collection of ungrouped times, print the total time.
270   // Ungrouped timers don't really make sense to add up.  We still print the
271   // TOTAL line to make the percentages make sense.
272   if (this != DefaultTimerGroup) {
273     *OutStream << "  Total Execution Time: ";
274     *OutStream << format("%5.4f", Total.getProcessTime()) << " seconds (";
275     *OutStream << format("%5.4f", Total.getWallTime()) << " wall clock)\n";
276   }
277   *OutStream << "\n";
278
279   if (Total.getUserTime())
280     *OutStream << "   ---User Time---";
281   if (Total.getSystemTime())
282     *OutStream << "   --System Time--";
283   if (Total.getProcessTime())
284     *OutStream << "   --User+System--";
285   *OutStream << "   ---Wall Time---";
286   if (Total.getMemUsed())
287     *OutStream << "  ---Mem---";
288   *OutStream << "  --- Name ---\n";
289
290   // Loop through all of the timing data, printing it out.
291   for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) {
292     const std::pair<TimeRecord, std::string> &Entry = TimersToPrint[e-i-1];
293     Entry.first.print(Total, *OutStream);
294     *OutStream << Entry.second << '\n';
295   }
296
297   Total.print(Total, *OutStream);
298   *OutStream << "Total\n\n";
299   OutStream->flush();
300
301   TimersToPrint.clear();
302
303   if (OutStream != &errs() && OutStream != &outs())
304     delete OutStream;   // Close the file.
305 }
306
307 void TimerGroup::addTimer() {
308   sys::SmartScopedLock<true> L(*TimerLock);
309   ++NumTimers;
310 }
311
312 void TimerGroup::addTimerToPrint(const TimeRecord &T, const std::string &Name) {
313   sys::SmartScopedLock<true> L(*TimerLock);
314   TimersToPrint.push_back(std::make_pair(T, Name));
315 }
316