1 //===-- Timer.cpp - Interval Timing Support -------------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // Interval Timing implementation.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/Timer.h"
15 #include "llvm/Support/CommandLine.h"
16 #include "llvm/Support/ManagedStatic.h"
17 #include "llvm/Support/Streams.h"
18 #include "llvm/System/Process.h"
25 // GetLibSupportInfoOutputFile - Return a file stream to print our output on.
26 namespace llvm
{ extern std::ostream
*GetLibSupportInfoOutputFile(); }
28 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
29 // of constructor/destructor ordering being unspecified by C++. Basically the
30 // problem is that a Statistic object gets destroyed, which ends up calling
31 // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
32 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
33 // would get destroyed before the Statistic, causing havoc to ensue. We "fix"
34 // this by creating the string the first time it is needed and never destroying
36 static ManagedStatic
<std::string
> LibSupportInfoOutputFilename
;
37 static std::string
&getLibSupportInfoOutputFilename() {
38 return *LibSupportInfoOutputFilename
;
43 TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
44 "tracking (this may be slow)"),
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()));
53 static TimerGroup
*DefaultTimerGroup
= 0;
54 static TimerGroup
*getDefaultTimerGroup() {
55 if (DefaultTimerGroup
) return DefaultTimerGroup
;
56 return DefaultTimerGroup
= new TimerGroup("Miscellaneous Ungrouped Timers");
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()) {
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
) {
71 Timer::Timer(const Timer
&T
) {
73 if (TG
) TG
->addTimer();
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
90 TG
->addTimerToPrint(*this);
96 static inline size_t getMemUsage() {
98 return sys::Process::GetMallocUsage();
103 double Elapsed
, UserTime
, SystemTime
;
107 static TimeRecord
getTimeRecord(bool Start
) {
110 sys::TimeValue
now(0,0);
111 sys::TimeValue
user(0,0);
112 sys::TimeValue
sys(0,0);
116 MemUsed
= getMemUsage();
117 sys::Process::GetTimeUsage(now
,user
,sys
);
119 sys::Process::GetTimeUsage(now
,user
,sys
);
120 MemUsed
= getMemUsage();
123 Result
.Elapsed
= now
.seconds() + now
.microseconds() / 1000000.0;
124 Result
.UserTime
= user
.seconds() + user
.microseconds() / 1000000.0;
125 Result
.SystemTime
= sys
.seconds() + sys
.microseconds() / 1000000.0;
126 Result
.MemUsed
= MemUsed
;
131 static ManagedStatic
<std::vector
<Timer
*> > ActiveTimers
;
133 void Timer::startTimer() {
135 TimeRecord TR
= getTimeRecord(true);
136 Elapsed
-= TR
.Elapsed
;
137 UserTime
-= TR
.UserTime
;
138 SystemTime
-= TR
.SystemTime
;
139 MemUsed
-= TR
.MemUsed
;
140 PeakMemBase
= TR
.MemUsed
;
141 ActiveTimers
->push_back(this);
144 void Timer::stopTimer() {
145 TimeRecord TR
= getTimeRecord(false);
146 Elapsed
+= TR
.Elapsed
;
147 UserTime
+= TR
.UserTime
;
148 SystemTime
+= TR
.SystemTime
;
149 MemUsed
+= TR
.MemUsed
;
151 if (ActiveTimers
->back() == this) {
152 ActiveTimers
->pop_back();
154 std::vector
<Timer
*>::iterator I
=
155 std::find(ActiveTimers
->begin(), ActiveTimers
->end(), this);
156 assert(I
!= ActiveTimers
->end() && "stop but no startTimer?");
157 ActiveTimers
->erase(I
);
161 void Timer::sum(const Timer
&T
) {
162 Elapsed
+= T
.Elapsed
;
163 UserTime
+= T
.UserTime
;
164 SystemTime
+= T
.SystemTime
;
165 MemUsed
+= T
.MemUsed
;
166 PeakMem
+= T
.PeakMem
;
169 /// addPeakMemoryMeasurement - This method should be called whenever memory
170 /// usage needs to be checked. It adds a peak memory measurement to the
171 /// currently active timers, which will be printed when the timer group prints
173 void Timer::addPeakMemoryMeasurement() {
174 size_t MemUsed
= getMemUsage();
176 for (std::vector
<Timer
*>::iterator I
= ActiveTimers
->begin(),
177 E
= ActiveTimers
->end(); I
!= E
; ++I
)
178 (*I
)->PeakMem
= std::max((*I
)->PeakMem
, MemUsed
-(*I
)->PeakMemBase
);
181 //===----------------------------------------------------------------------===//
182 // NamedRegionTimer Implementation
183 //===----------------------------------------------------------------------===//
185 static ManagedStatic
<std::map
<std::string
, Timer
> > NamedTimers
;
187 static Timer
&getNamedRegionTimer(const std::string
&Name
) {
188 std::map
<std::string
, Timer
>::iterator I
= NamedTimers
->lower_bound(Name
);
189 if (I
!= NamedTimers
->end() && I
->first
== Name
)
192 return NamedTimers
->insert(I
, std::make_pair(Name
, Timer(Name
)))->second
;
195 NamedRegionTimer::NamedRegionTimer(const std::string
&Name
)
196 : TimeRegion(getNamedRegionTimer(Name
)) {}
199 //===----------------------------------------------------------------------===//
200 // TimerGroup Implementation
201 //===----------------------------------------------------------------------===//
203 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
204 // TotalWidth size, and B is the AfterDec size.
206 static void printAlignedFP(double Val
, unsigned AfterDec
, unsigned TotalWidth
,
208 assert(TotalWidth
>= AfterDec
+1 && "Bad FP Format!");
209 OS
.width(TotalWidth
-AfterDec
-1);
210 char OldFill
= OS
.fill();
212 OS
<< (int)Val
; // Integer part;
216 unsigned ResultFieldSize
= 1;
217 while (AfterDec
--) ResultFieldSize
*= 10;
218 OS
<< (int)(Val
*ResultFieldSize
) % ResultFieldSize
;
222 static void printVal(double Val
, double Total
, std::ostream
&OS
) {
223 if (Total
< 1e-7) // Avoid dividing by zero...
227 printAlignedFP(Val
, 4, 7, OS
);
229 printAlignedFP(Val
*100/Total
, 1, 5, OS
);
234 void Timer::print(const Timer
&Total
, std::ostream
&OS
) {
236 printVal(UserTime
, Total
.UserTime
, OS
);
237 if (Total
.SystemTime
)
238 printVal(SystemTime
, Total
.SystemTime
, OS
);
239 if (Total
.getProcessTime())
240 printVal(getProcessTime(), Total
.getProcessTime(), OS
);
241 printVal(Elapsed
, Total
.Elapsed
, OS
);
247 OS
<< MemUsed
<< " ";
252 OS
<< PeakMem
<< " ";
258 Started
= false; // Once printed, don't print again
261 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
263 llvm::GetLibSupportInfoOutputFile() {
264 std::string
&LibSupportInfoOutputFilename
= getLibSupportInfoOutputFilename();
265 if (LibSupportInfoOutputFilename
.empty())
266 return cerr
.stream();
267 if (LibSupportInfoOutputFilename
== "-")
268 return cout
.stream();
270 std::ostream
*Result
= new std::ofstream(LibSupportInfoOutputFilename
.c_str(),
272 if (!Result
->good()) {
273 cerr
<< "Error opening info-output-file '"
274 << LibSupportInfoOutputFilename
<< " for appending!\n";
276 return cerr
.stream();
282 void TimerGroup::removeTimer() {
283 if (--NumTimers
== 0 && !TimersToPrint
.empty()) { // Print timing report...
284 // Sort the timers in descending order by amount of time taken...
285 std::sort(TimersToPrint
.begin(), TimersToPrint
.end(),
286 std::greater
<Timer
>());
288 // Figure out how many spaces to indent TimerGroup name...
289 unsigned Padding
= (80-Name
.length())/2;
290 if (Padding
> 80) Padding
= 0; // Don't allow "negative" numbers
292 std::ostream
*OutStream
= GetLibSupportInfoOutputFile();
295 { // Scope to contain Total timer... don't allow total timer to drop us to
297 Timer
Total("TOTAL");
299 for (unsigned i
= 0, e
= TimersToPrint
.size(); i
!= e
; ++i
)
300 Total
.sum(TimersToPrint
[i
]);
302 // Print out timing header...
303 *OutStream
<< "===" << std::string(73, '-') << "===\n"
304 << std::string(Padding
, ' ') << Name
<< "\n"
305 << "===" << std::string(73, '-')
308 // If this is not an collection of ungrouped times, print the total time.
309 // Ungrouped timers don't really make sense to add up. We still print the
310 // TOTAL line to make the percentages make sense.
311 if (this != DefaultTimerGroup
) {
312 *OutStream
<< " Total Execution Time: ";
314 printAlignedFP(Total
.getProcessTime(), 4, 5, *OutStream
);
315 *OutStream
<< " seconds (";
316 printAlignedFP(Total
.getWallTime(), 4, 5, *OutStream
);
317 *OutStream
<< " wall clock)\n";
322 *OutStream
<< " ---User Time---";
323 if (Total
.SystemTime
)
324 *OutStream
<< " --System Time--";
325 if (Total
.getProcessTime())
326 *OutStream
<< " --User+System--";
327 *OutStream
<< " ---Wall Time---";
328 if (Total
.getMemUsed())
329 *OutStream
<< " ---Mem---";
330 if (Total
.getPeakMem())
331 *OutStream
<< " -PeakMem-";
332 *OutStream
<< " --- Name ---\n";
334 // Loop through all of the timing data, printing it out...
335 for (unsigned i
= 0, e
= TimersToPrint
.size(); i
!= e
; ++i
)
336 TimersToPrint
[i
].print(Total
, *OutStream
);
338 Total
.print(Total
, *OutStream
);
339 *OutStream
<< std::endl
; // Flush output
343 TimersToPrint
.clear();
345 if (OutStream
!= cerr
.stream() && OutStream
!= cout
.stream())
346 delete OutStream
; // Close the file...
349 // Delete default timer group!
350 if (NumTimers
== 0 && this == DefaultTimerGroup
) {
351 delete DefaultTimerGroup
;
352 DefaultTimerGroup
= 0;