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