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
;
41 static ManagedStatic
<sys::SmartMutex
<true> > TimerLock
;
45 TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
46 "tracking (this may be slow)"),
49 static cl::opt
<std::string
, true>
50 InfoOutputFilename("info-output-file", cl::value_desc("filename"),
51 cl::desc("File to append -stats and -timer output to"),
52 cl::Hidden
, cl::location(getLibSupportInfoOutputFilename()));
55 static TimerGroup
*DefaultTimerGroup
= 0;
56 static TimerGroup
*getDefaultTimerGroup() {
57 TimerGroup
* tmp
= DefaultTimerGroup
;
60 llvm_acquire_global_lock();
61 tmp
= DefaultTimerGroup
;
63 tmp
= new TimerGroup("Miscellaneous Ungrouped Timers");
65 DefaultTimerGroup
= tmp
;
67 llvm_release_global_lock();
73 Timer::Timer(const std::string
&N
)
74 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N
),
75 Started(false), TG(getDefaultTimerGroup()) {
79 Timer::Timer(const std::string
&N
, TimerGroup
&tg
)
80 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N
),
81 Started(false), TG(&tg
) {
85 Timer::Timer(const Timer
&T
) {
87 if (TG
) TG
->addTimer();
92 // Copy ctor, initialize with no TG member.
93 Timer::Timer(bool, const Timer
&T
) {
94 TG
= T
.TG
; // Avoid assertion in operator=
95 operator=(T
); // Copy contents
104 TG
->addTimerToPrint(*this);
110 static inline size_t getMemUsage() {
112 return sys::Process::GetMallocUsage();
117 double Elapsed
, UserTime
, SystemTime
;
121 static TimeRecord
getTimeRecord(bool Start
) {
124 sys::TimeValue
now(0,0);
125 sys::TimeValue
user(0,0);
126 sys::TimeValue
sys(0,0);
130 MemUsed
= getMemUsage();
131 sys::Process::GetTimeUsage(now
,user
,sys
);
133 sys::Process::GetTimeUsage(now
,user
,sys
);
134 MemUsed
= getMemUsage();
137 Result
.Elapsed
= now
.seconds() + now
.microseconds() / 1000000.0;
138 Result
.UserTime
= user
.seconds() + user
.microseconds() / 1000000.0;
139 Result
.SystemTime
= sys
.seconds() + sys
.microseconds() / 1000000.0;
140 Result
.MemUsed
= MemUsed
;
145 static ManagedStatic
<std::vector
<Timer
*> > ActiveTimers
;
147 void Timer::startTimer() {
148 sys::SmartScopedLock
<true> L(Lock
);
150 ActiveTimers
->push_back(this);
151 TimeRecord TR
= getTimeRecord(true);
152 Elapsed
-= TR
.Elapsed
;
153 UserTime
-= TR
.UserTime
;
154 SystemTime
-= TR
.SystemTime
;
155 MemUsed
-= TR
.MemUsed
;
156 PeakMemBase
= TR
.MemUsed
;
159 void Timer::stopTimer() {
160 sys::SmartScopedLock
<true> L(Lock
);
161 TimeRecord TR
= getTimeRecord(false);
162 Elapsed
+= TR
.Elapsed
;
163 UserTime
+= TR
.UserTime
;
164 SystemTime
+= TR
.SystemTime
;
165 MemUsed
+= TR
.MemUsed
;
167 if (ActiveTimers
->back() == this) {
168 ActiveTimers
->pop_back();
170 std::vector
<Timer
*>::iterator I
=
171 std::find(ActiveTimers
->begin(), ActiveTimers
->end(), this);
172 assert(I
!= ActiveTimers
->end() && "stop but no startTimer?");
173 ActiveTimers
->erase(I
);
177 void Timer::sum(const Timer
&T
) {
186 Elapsed
+= T
.Elapsed
;
187 UserTime
+= T
.UserTime
;
188 SystemTime
+= T
.SystemTime
;
189 MemUsed
+= T
.MemUsed
;
190 PeakMem
+= T
.PeakMem
;
201 /// addPeakMemoryMeasurement - This method should be called whenever memory
202 /// usage needs to be checked. It adds a peak memory measurement to the
203 /// currently active timers, which will be printed when the timer group prints
205 void Timer::addPeakMemoryMeasurement() {
206 size_t MemUsed
= getMemUsage();
208 for (std::vector
<Timer
*>::iterator I
= ActiveTimers
->begin(),
209 E
= ActiveTimers
->end(); I
!= E
; ++I
) {
210 (*I
)->Lock
.acquire();
211 (*I
)->PeakMem
= std::max((*I
)->PeakMem
, MemUsed
-(*I
)->PeakMemBase
);
212 (*I
)->Lock
.release();
216 //===----------------------------------------------------------------------===//
217 // NamedRegionTimer Implementation
218 //===----------------------------------------------------------------------===//
222 typedef std::map
<std::string
, Timer
> Name2Timer
;
223 typedef std::map
<std::string
, std::pair
<TimerGroup
, Name2Timer
> > Name2Pair
;
227 static ManagedStatic
<Name2Timer
> NamedTimers
;
229 static ManagedStatic
<Name2Pair
> NamedGroupedTimers
;
231 static Timer
&getNamedRegionTimer(const std::string
&Name
) {
232 sys::SmartScopedLock
<true> L(*TimerLock
);
233 Name2Timer::iterator I
= NamedTimers
->find(Name
);
234 if (I
!= NamedTimers
->end())
237 return NamedTimers
->insert(I
, std::make_pair(Name
, Timer(Name
)))->second
;
240 static Timer
&getNamedRegionTimer(const std::string
&Name
,
241 const std::string
&GroupName
) {
242 sys::SmartScopedLock
<true> L(*TimerLock
);
244 Name2Pair::iterator I
= NamedGroupedTimers
->find(GroupName
);
245 if (I
== NamedGroupedTimers
->end()) {
246 TimerGroup
TG(GroupName
);
247 std::pair
<TimerGroup
, Name2Timer
> Pair(TG
, Name2Timer());
248 I
= NamedGroupedTimers
->insert(I
, std::make_pair(GroupName
, Pair
));
251 Name2Timer::iterator J
= I
->second
.second
.find(Name
);
252 if (J
== I
->second
.second
.end())
253 J
= I
->second
.second
.insert(J
,
261 NamedRegionTimer::NamedRegionTimer(const std::string
&Name
)
262 : TimeRegion(getNamedRegionTimer(Name
)) {}
264 NamedRegionTimer::NamedRegionTimer(const std::string
&Name
,
265 const std::string
&GroupName
)
266 : TimeRegion(getNamedRegionTimer(Name
, GroupName
)) {}
268 //===----------------------------------------------------------------------===//
269 // TimerGroup Implementation
270 //===----------------------------------------------------------------------===//
272 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
273 // TotalWidth size, and B is the AfterDec size.
275 static void printAlignedFP(double Val
, unsigned AfterDec
, unsigned TotalWidth
,
277 assert(TotalWidth
>= AfterDec
+1 && "Bad FP Format!");
278 OS
.width(TotalWidth
-AfterDec
-1);
279 char OldFill
= OS
.fill();
281 OS
<< (int)Val
; // Integer part;
285 unsigned ResultFieldSize
= 1;
286 while (AfterDec
--) ResultFieldSize
*= 10;
287 OS
<< (int)(Val
*ResultFieldSize
) % ResultFieldSize
;
291 static void printVal(double Val
, double Total
, std::ostream
&OS
) {
292 if (Total
< 1e-7) // Avoid dividing by zero...
296 printAlignedFP(Val
, 4, 7, OS
);
298 printAlignedFP(Val
*100/Total
, 1, 5, OS
);
303 void Timer::print(const Timer
&Total
, std::ostream
&OS
) {
305 Total
.Lock
.acquire();
309 Total
.Lock
.acquire();
313 printVal(UserTime
, Total
.UserTime
, OS
);
314 if (Total
.SystemTime
)
315 printVal(SystemTime
, Total
.SystemTime
, OS
);
316 if (Total
.getProcessTime())
317 printVal(getProcessTime(), Total
.getProcessTime(), OS
);
318 printVal(Elapsed
, Total
.Elapsed
, OS
);
324 OS
<< MemUsed
<< " ";
329 OS
<< PeakMem
<< " ";
335 Started
= false; // Once printed, don't print again
338 Total
.Lock
.release();
342 Total
.Lock
.release();
346 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
348 llvm::GetLibSupportInfoOutputFile() {
349 std::string
&LibSupportInfoOutputFilename
= getLibSupportInfoOutputFilename();
350 if (LibSupportInfoOutputFilename
.empty())
351 return cerr
.stream();
352 if (LibSupportInfoOutputFilename
== "-")
353 return cout
.stream();
355 std::ostream
*Result
= new std::ofstream(LibSupportInfoOutputFilename
.c_str(),
357 if (!Result
->good()) {
358 cerr
<< "Error opening info-output-file '"
359 << LibSupportInfoOutputFilename
<< " for appending!\n";
361 return cerr
.stream();
367 void TimerGroup::removeTimer() {
368 sys::SmartScopedLock
<true> L(*TimerLock
);
369 if (--NumTimers
== 0 && !TimersToPrint
.empty()) { // Print timing report...
370 // Sort the timers in descending order by amount of time taken...
371 std::sort(TimersToPrint
.begin(), TimersToPrint
.end(),
372 std::greater
<Timer
>());
374 // Figure out how many spaces to indent TimerGroup name...
375 unsigned Padding
= (80-Name
.length())/2;
376 if (Padding
> 80) Padding
= 0; // Don't allow "negative" numbers
378 std::ostream
*OutStream
= GetLibSupportInfoOutputFile();
381 { // Scope to contain Total timer... don't allow total timer to drop us to
383 Timer
Total("TOTAL");
385 for (unsigned i
= 0, e
= TimersToPrint
.size(); i
!= e
; ++i
)
386 Total
.sum(TimersToPrint
[i
]);
388 // Print out timing header...
389 *OutStream
<< "===" << std::string(73, '-') << "===\n"
390 << std::string(Padding
, ' ') << Name
<< "\n"
391 << "===" << std::string(73, '-')
394 // If this is not an collection of ungrouped times, print the total time.
395 // Ungrouped timers don't really make sense to add up. We still print the
396 // TOTAL line to make the percentages make sense.
397 if (this != DefaultTimerGroup
) {
398 *OutStream
<< " Total Execution Time: ";
400 printAlignedFP(Total
.getProcessTime(), 4, 5, *OutStream
);
401 *OutStream
<< " seconds (";
402 printAlignedFP(Total
.getWallTime(), 4, 5, *OutStream
);
403 *OutStream
<< " wall clock)\n";
408 *OutStream
<< " ---User Time---";
409 if (Total
.SystemTime
)
410 *OutStream
<< " --System Time--";
411 if (Total
.getProcessTime())
412 *OutStream
<< " --User+System--";
413 *OutStream
<< " ---Wall Time---";
414 if (Total
.getMemUsed())
415 *OutStream
<< " ---Mem---";
416 if (Total
.getPeakMem())
417 *OutStream
<< " -PeakMem-";
418 *OutStream
<< " --- Name ---\n";
420 // Loop through all of the timing data, printing it out...
421 for (unsigned i
= 0, e
= TimersToPrint
.size(); i
!= e
; ++i
)
422 TimersToPrint
[i
].print(Total
, *OutStream
);
424 Total
.print(Total
, *OutStream
);
425 *OutStream
<< std::endl
; // Flush output
429 TimersToPrint
.clear();
431 if (OutStream
!= cerr
.stream() && OutStream
!= cout
.stream())
432 delete OutStream
; // Close the file...
436 void TimerGroup::addTimer() {
437 sys::SmartScopedLock
<true> L(*TimerLock
);
441 void TimerGroup::addTimerToPrint(const Timer
&T
) {
442 sys::SmartScopedLock
<true> L(*TimerLock
);
443 TimersToPrint
.push_back(Timer(true, T
));