1 //===-- Timer.cpp - Interval Timing Support -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 static 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 ActiveTimers
->push_back(this);
136 TimeRecord TR
= getTimeRecord(true);
137 Elapsed
-= TR
.Elapsed
;
138 UserTime
-= TR
.UserTime
;
139 SystemTime
-= TR
.SystemTime
;
140 MemUsed
-= TR
.MemUsed
;
141 PeakMemBase
= TR
.MemUsed
;
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 //===----------------------------------------------------------------------===//
187 typedef std::map
<std::string
, Timer
> Name2Timer
;
188 typedef std::map
<std::string
, std::pair
<TimerGroup
, Name2Timer
> > Name2Pair
;
192 static ManagedStatic
<Name2Timer
> NamedTimers
;
194 static ManagedStatic
<Name2Pair
> NamedGroupedTimers
;
196 static Timer
&getNamedRegionTimer(const std::string
&Name
) {
197 Name2Timer::iterator I
= NamedTimers
->find(Name
);
198 if (I
!= NamedTimers
->end())
201 return NamedTimers
->insert(I
, std::make_pair(Name
, Timer(Name
)))->second
;
204 static Timer
&getNamedRegionTimer(const std::string
&Name
,
205 const std::string
&GroupName
) {
207 Name2Pair::iterator I
= NamedGroupedTimers
->find(GroupName
);
208 if (I
== NamedGroupedTimers
->end()) {
209 TimerGroup
TG(GroupName
);
210 std::pair
<TimerGroup
, Name2Timer
> Pair(TG
, Name2Timer());
211 I
= NamedGroupedTimers
->insert(I
, std::make_pair(GroupName
, Pair
));
214 Name2Timer::iterator J
= I
->second
.second
.find(Name
);
215 if (J
== I
->second
.second
.end())
216 J
= I
->second
.second
.insert(J
,
224 NamedRegionTimer::NamedRegionTimer(const std::string
&Name
)
225 : TimeRegion(getNamedRegionTimer(Name
)) {}
227 NamedRegionTimer::NamedRegionTimer(const std::string
&Name
,
228 const std::string
&GroupName
)
229 : TimeRegion(getNamedRegionTimer(Name
, GroupName
)) {}
231 //===----------------------------------------------------------------------===//
232 // TimerGroup Implementation
233 //===----------------------------------------------------------------------===//
235 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
236 // TotalWidth size, and B is the AfterDec size.
238 static void printAlignedFP(double Val
, unsigned AfterDec
, unsigned TotalWidth
,
240 assert(TotalWidth
>= AfterDec
+1 && "Bad FP Format!");
241 OS
.width(TotalWidth
-AfterDec
-1);
242 char OldFill
= OS
.fill();
244 OS
<< (int)Val
; // Integer part;
248 unsigned ResultFieldSize
= 1;
249 while (AfterDec
--) ResultFieldSize
*= 10;
250 OS
<< (int)(Val
*ResultFieldSize
) % ResultFieldSize
;
254 static void printVal(double Val
, double Total
, std::ostream
&OS
) {
255 if (Total
< 1e-7) // Avoid dividing by zero...
259 printAlignedFP(Val
, 4, 7, OS
);
261 printAlignedFP(Val
*100/Total
, 1, 5, OS
);
266 void Timer::print(const Timer
&Total
, std::ostream
&OS
) {
268 printVal(UserTime
, Total
.UserTime
, OS
);
269 if (Total
.SystemTime
)
270 printVal(SystemTime
, Total
.SystemTime
, OS
);
271 if (Total
.getProcessTime())
272 printVal(getProcessTime(), Total
.getProcessTime(), OS
);
273 printVal(Elapsed
, Total
.Elapsed
, OS
);
279 OS
<< MemUsed
<< " ";
284 OS
<< PeakMem
<< " ";
290 Started
= false; // Once printed, don't print again
293 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
295 llvm::GetLibSupportInfoOutputFile() {
296 std::string
&LibSupportInfoOutputFilename
= getLibSupportInfoOutputFilename();
297 if (LibSupportInfoOutputFilename
.empty())
298 return cerr
.stream();
299 if (LibSupportInfoOutputFilename
== "-")
300 return cout
.stream();
302 std::ostream
*Result
= new std::ofstream(LibSupportInfoOutputFilename
.c_str(),
304 if (!Result
->good()) {
305 cerr
<< "Error opening info-output-file '"
306 << LibSupportInfoOutputFilename
<< " for appending!\n";
308 return cerr
.stream();
314 void TimerGroup::removeTimer() {
315 if (--NumTimers
== 0 && !TimersToPrint
.empty()) { // Print timing report...
316 // Sort the timers in descending order by amount of time taken...
317 std::sort(TimersToPrint
.begin(), TimersToPrint
.end(),
318 std::greater
<Timer
>());
320 // Figure out how many spaces to indent TimerGroup name...
321 unsigned Padding
= (80-Name
.length())/2;
322 if (Padding
> 80) Padding
= 0; // Don't allow "negative" numbers
324 std::ostream
*OutStream
= GetLibSupportInfoOutputFile();
327 { // Scope to contain Total timer... don't allow total timer to drop us to
329 Timer
Total("TOTAL");
331 for (unsigned i
= 0, e
= TimersToPrint
.size(); i
!= e
; ++i
)
332 Total
.sum(TimersToPrint
[i
]);
334 // Print out timing header...
335 *OutStream
<< "===" << std::string(73, '-') << "===\n"
336 << std::string(Padding
, ' ') << Name
<< "\n"
337 << "===" << std::string(73, '-')
340 // If this is not an collection of ungrouped times, print the total time.
341 // Ungrouped timers don't really make sense to add up. We still print the
342 // TOTAL line to make the percentages make sense.
343 if (this != DefaultTimerGroup
) {
344 *OutStream
<< " Total Execution Time: ";
346 printAlignedFP(Total
.getProcessTime(), 4, 5, *OutStream
);
347 *OutStream
<< " seconds (";
348 printAlignedFP(Total
.getWallTime(), 4, 5, *OutStream
);
349 *OutStream
<< " wall clock)\n";
354 *OutStream
<< " ---User Time---";
355 if (Total
.SystemTime
)
356 *OutStream
<< " --System Time--";
357 if (Total
.getProcessTime())
358 *OutStream
<< " --User+System--";
359 *OutStream
<< " ---Wall Time---";
360 if (Total
.getMemUsed())
361 *OutStream
<< " ---Mem---";
362 if (Total
.getPeakMem())
363 *OutStream
<< " -PeakMem-";
364 *OutStream
<< " --- Name ---\n";
366 // Loop through all of the timing data, printing it out...
367 for (unsigned i
= 0, e
= TimersToPrint
.size(); i
!= e
; ++i
)
368 TimersToPrint
[i
].print(Total
, *OutStream
);
370 Total
.print(Total
, *OutStream
);
371 *OutStream
<< std::endl
; // Flush output
375 TimersToPrint
.clear();
377 if (OutStream
!= cerr
.stream() && OutStream
!= cout
.stream())
378 delete OutStream
; // Close the file...
381 // Delete default timer group!
382 if (NumTimers
== 0 && this == DefaultTimerGroup
) {
383 delete DefaultTimerGroup
;
384 DefaultTimerGroup
= 0;