30a7fbb3bd17bcf2f0dd3be77f06a1ff28987938
[oota-llvm.git] / lib / Support / Timer.cpp
1 //===-- Timer.cpp - Interval Timing Support -------------------------------===//
2 //
3 // Interval Timing implementation.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "Support/Timer.h"
8 #include "Support/CommandLine.h"
9 #include "Config/sys/resource.h"
10 #include "Config/sys/time.h"
11 #include "Config/unistd.h"
12 #include "Config/malloc.h"
13 #include <iostream>
14 #include <algorithm>
15 #include <functional>
16 #include <fstream>
17 #include <map>
18
19 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
20 // of constructor/destructor ordering being unspecified by C++.  Basically the
21 // problem is that a Statistic<> object gets destroyed, which ends up calling
22 // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
23 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
24 // would get destroyed before the Statistic, causing havoc to ensue.  We "fix"
25 // this by creating the string the first time it is needed and never destroying
26 // it.
27 static std::string &getLibSupportInfoOutputFilename() {
28   static std::string *LibSupportInfoOutputFilename = new std::string();
29   return *LibSupportInfoOutputFilename;
30 }
31
32 namespace {
33 #ifdef HAVE_MALLINFO
34   cl::opt<bool>
35   TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
36                                       "tracking (this may be slow)"),
37              cl::Hidden);
38 #endif
39
40   cl::opt<std::string, true>
41   InfoOutputFilename("info-output-file", cl::value_desc("filename"),
42                      cl::desc("File to append -stats and -timer output to"),
43                    cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
44 }
45
46 static TimerGroup *DefaultTimerGroup = 0;
47 static TimerGroup *getDefaultTimerGroup() {
48   if (DefaultTimerGroup) return DefaultTimerGroup;
49   return DefaultTimerGroup = new TimerGroup("Miscellaneous Ungrouped Timers");
50 }
51
52 Timer::Timer(const std::string &N)
53   : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
54     Started(false), TG(getDefaultTimerGroup()) {
55   TG->addTimer();
56 }
57
58 Timer::Timer(const std::string &N, TimerGroup &tg)
59   : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
60     Started(false), TG(&tg) {
61   TG->addTimer();
62 }
63
64 Timer::Timer(const Timer &T) {
65   TG = T.TG;
66   if (TG) TG->addTimer();
67   operator=(T);
68 }
69
70
71 // Copy ctor, initialize with no TG member.
72 Timer::Timer(bool, const Timer &T) {
73   TG = T.TG;     // Avoid assertion in operator=
74   operator=(T);  // Copy contents
75   TG = 0;
76 }
77
78
79 Timer::~Timer() {
80   if (TG) {
81     if (Started) {
82       Started = false;
83       TG->addTimerToPrint(*this);
84     }
85     TG->removeTimer();
86   }
87 }
88
89 static long getMemUsage() {
90 #ifdef HAVE_MALLINFO
91   if (TrackSpace) {
92     struct mallinfo MI = mallinfo();
93     return MI.uordblks/*+MI.hblkhd*/;
94   }
95 #endif
96   return 0;
97 }
98
99 struct TimeRecord {
100   double Elapsed, UserTime, SystemTime;
101   long MemUsed;
102 };
103
104 static TimeRecord getTimeRecord(bool Start) {
105   struct rusage RU;
106   struct timeval T;
107   long MemUsed = 0;
108   if (Start) {
109     MemUsed = getMemUsage();
110     if (getrusage(RUSAGE_SELF, &RU))
111       perror("getrusage call failed: -time-passes info incorrect!");
112   }
113   gettimeofday(&T, 0);
114
115   if (!Start) {
116     MemUsed = getMemUsage();
117     if (getrusage(RUSAGE_SELF, &RU))
118       perror("getrusage call failed: -time-passes info incorrect!");
119   }
120
121   TimeRecord Result;
122   Result.Elapsed    =           T.tv_sec +           T.tv_usec/1000000.0;
123   Result.UserTime   = RU.ru_utime.tv_sec + RU.ru_utime.tv_usec/1000000.0;
124   Result.SystemTime = RU.ru_stime.tv_sec + RU.ru_stime.tv_usec/1000000.0;
125   Result.MemUsed = MemUsed;
126
127   return Result;
128 }
129
130 static std::vector<Timer*> ActiveTimers;
131
132 void Timer::startTimer() {
133   Started = true;
134   TimeRecord TR = getTimeRecord(true);
135   Elapsed    -= TR.Elapsed;
136   UserTime   -= TR.UserTime;
137   SystemTime -= TR.SystemTime;
138   MemUsed    -= TR.MemUsed;
139   PeakMemBase = TR.MemUsed;
140   ActiveTimers.push_back(this);
141 }
142
143 void Timer::stopTimer() {
144   TimeRecord TR = getTimeRecord(false);
145   Elapsed    += TR.Elapsed;
146   UserTime   += TR.UserTime;
147   SystemTime += TR.SystemTime;
148   MemUsed    += TR.MemUsed;
149
150   if (ActiveTimers.back() == this) {
151     ActiveTimers.pop_back();
152   } else {
153     std::vector<Timer*>::iterator I =
154       std::find(ActiveTimers.begin(), ActiveTimers.end(), this);
155     assert(I != ActiveTimers.end() && "stop but no startTimer?");
156     ActiveTimers.erase(I);
157   }
158 }
159
160 void Timer::sum(const Timer &T) {
161   Elapsed    += T.Elapsed;
162   UserTime   += T.UserTime;
163   SystemTime += T.SystemTime;
164   MemUsed    += T.MemUsed;
165   PeakMem    += T.PeakMem;
166 }
167
168 /// addPeakMemoryMeasurement - This method should be called whenever memory
169 /// usage needs to be checked.  It adds a peak memory measurement to the
170 /// currently active timers, which will be printed when the timer group prints
171 ///
172 void Timer::addPeakMemoryMeasurement() {
173   long MemUsed = getMemUsage();
174
175   for (std::vector<Timer*>::iterator I = ActiveTimers.begin(),
176          E = ActiveTimers.end(); I != E; ++I)
177     (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase);
178 }
179
180 //===----------------------------------------------------------------------===//
181 //   NamedRegionTimer Implementation
182 //===----------------------------------------------------------------------===//
183
184 static Timer &getNamedRegionTimer(const std::string &Name) {
185   static std::map<std::string, Timer> NamedTimers;
186
187   std::map<std::string, Timer>::iterator I = NamedTimers.lower_bound(Name);
188   if (I != NamedTimers.end() && I->first == Name)
189     return I->second;
190
191   return NamedTimers.insert(I, std::make_pair(Name, Timer(Name)))->second;
192 }
193
194 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
195   : TimeRegion(getNamedRegionTimer(Name)) {}
196
197
198 //===----------------------------------------------------------------------===//
199 //   TimerGroup Implementation
200 //===----------------------------------------------------------------------===//
201
202 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
203 // TotalWidth size, and B is the AfterDec size.
204 //
205 static void printAlignedFP(double Val, unsigned AfterDec, unsigned TotalWidth,
206                            std::ostream &OS) {
207   assert(TotalWidth >= AfterDec+1 && "Bad FP Format!");
208   OS.width(TotalWidth-AfterDec-1);
209   char OldFill = OS.fill();
210   OS.fill(' ');
211   OS << (int)Val;  // Integer part;
212   OS << ".";
213   OS.width(AfterDec);
214   OS.fill('0');
215   unsigned ResultFieldSize = 1;
216   while (AfterDec--) ResultFieldSize *= 10;
217   OS << (int)(Val*ResultFieldSize) % ResultFieldSize;
218   OS.fill(OldFill);
219 }
220
221 static void printVal(double Val, double Total, std::ostream &OS) {
222   if (Total < 1e-7)   // Avoid dividing by zero...
223     OS << "        -----     ";
224   else {
225     OS << "  ";
226     printAlignedFP(Val, 4, 7, OS);
227     OS << " (";
228     printAlignedFP(Val*100/Total, 1, 5, OS);
229     OS << "%)";
230   }
231 }
232
233 void Timer::print(const Timer &Total, std::ostream &OS) {
234   if (Total.UserTime)
235     printVal(UserTime, Total.UserTime, OS);
236   if (Total.SystemTime)
237     printVal(SystemTime, Total.SystemTime, OS);
238   if (Total.getProcessTime())
239     printVal(getProcessTime(), Total.getProcessTime(), OS);
240   printVal(Elapsed, Total.Elapsed, OS);
241   
242   OS << "  ";
243
244   if (Total.MemUsed) {
245     OS.width(9);
246     OS << MemUsed << "  ";
247   }
248   if (Total.PeakMem) {
249     if (PeakMem) {
250       OS.width(9);
251       OS << PeakMem << "  ";
252     } else
253       OS << "           ";
254   }
255   OS << Name << "\n";
256
257   Started = false;  // Once printed, don't print again
258 }
259
260 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
261 std::ostream *GetLibSupportInfoOutputFile() {
262   std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
263   if (LibSupportInfoOutputFilename.empty())
264     return &std::cerr;
265   if (LibSupportInfoOutputFilename == "-")
266     return &std::cout;
267
268   std::ostream *Result = new std::ofstream(LibSupportInfoOutputFilename.c_str(),
269                                            std::ios::app);
270   if (!Result->good()) {
271     std::cerr << "Error opening info-output-file '"
272               << LibSupportInfoOutputFilename << " for appending!\n";
273     delete Result;
274     return &std::cerr;
275   }
276   return Result;
277 }
278
279
280 void TimerGroup::removeTimer() {
281   if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report...
282     // Sort the timers in descending order by amount of time taken...
283     std::sort(TimersToPrint.begin(), TimersToPrint.end(),
284               std::greater<Timer>());
285
286     // Figure out how many spaces to indent TimerGroup name...
287     unsigned Padding = (80-Name.length())/2;
288     if (Padding > 80) Padding = 0;         // Don't allow "negative" numbers
289
290     std::ostream *OutStream = GetLibSupportInfoOutputFile();
291
292     ++NumTimers;
293     {  // Scope to contain Total timer... don't allow total timer to drop us to
294        // zero timers...
295       Timer Total("TOTAL");
296   
297       for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
298         Total.sum(TimersToPrint[i]);
299       
300       // Print out timing header...
301       *OutStream << "===" << std::string(73, '-') << "===\n"
302                  << std::string(Padding, ' ') << Name << "\n"
303                  << "===" << std::string(73, '-')
304                  << "===\n  Total Execution Time: ";
305
306       printAlignedFP(Total.getProcessTime(), 4, 5, *OutStream);
307       *OutStream << " seconds (";
308       printAlignedFP(Total.getWallTime(), 4, 5, *OutStream);
309       *OutStream << " wall clock)\n\n";
310
311       if (Total.UserTime)
312         *OutStream << "   ---User Time---";
313       if (Total.SystemTime)
314         *OutStream << "   --System Time--";
315       if (Total.getProcessTime())
316         *OutStream << "   --User+System--";
317       *OutStream << "   ---Wall Time---";
318       if (Total.getMemUsed())
319         *OutStream << "  ---Mem---";
320       if (Total.getPeakMem())
321         *OutStream << "  -PeakMem-";
322       *OutStream << "  --- Name ---\n";
323       
324       // Loop through all of the timing data, printing it out...
325       for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
326         TimersToPrint[i].print(Total, *OutStream);
327     
328       Total.print(Total, *OutStream);
329       *OutStream << std::endl;  // Flush output
330     }
331     --NumTimers;
332
333     TimersToPrint.clear();
334
335     if (OutStream != &std::cerr && OutStream != &std::cout)
336       delete OutStream;   // Close the file...
337   }
338
339   // Delete default timer group!
340   if (NumTimers == 0 && this == DefaultTimerGroup) {
341     delete DefaultTimerGroup;
342     DefaultTimerGroup = 0;
343   }
344 }