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