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