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 TimerGroup* tmp = DefaultTimerGroup;
58 llvm_acquire_global_lock();
59 tmp = DefaultTimerGroup;
61 tmp = new TimerGroup("Miscellaneous Ungrouped Timers");
63 DefaultTimerGroup = tmp;
65 llvm_release_global_lock();
71 Timer::Timer(const std::string &N)
72 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
73 Started(false), TG(getDefaultTimerGroup()) {
77 Timer::Timer(const std::string &N, TimerGroup &tg)
78 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
79 Started(false), TG(&tg) {
83 Timer::Timer(const Timer &T) {
85 if (TG) TG->addTimer();
90 // Copy ctor, initialize with no TG member.
91 Timer::Timer(bool, const Timer &T) {
92 TG = T.TG; // Avoid assertion in operator=
93 operator=(T); // Copy contents
102 TG->addTimerToPrint(*this);
108 static inline size_t getMemUsage() {
110 return sys::Process::GetMallocUsage();
115 uint64_t Elapsed, UserTime, SystemTime, MemUsed;
118 static TimeRecord getTimeRecord(bool Start) {
121 sys::TimeValue now(0,0);
122 sys::TimeValue user(0,0);
123 sys::TimeValue sys(0,0);
125 uint64_t MemUsed = 0;
127 MemUsed = getMemUsage();
128 sys::Process::GetTimeUsage(now,user,sys);
130 sys::Process::GetTimeUsage(now,user,sys);
131 MemUsed = getMemUsage();
134 Result.Elapsed = now.seconds() * 1000000 + now.microseconds();
135 Result.UserTime = user.seconds() * 1000000 + user.microseconds();
136 Result.SystemTime = sys.seconds() * 1000000 + sys.microseconds();
137 Result.MemUsed = MemUsed;
142 static ManagedStatic<std::vector<Timer*> > ActiveTimers;
144 void Timer::startTimer() {
146 ActiveTimers->push_back(this);
147 TimeRecord TR = getTimeRecord(true);
148 Elapsed -= TR.Elapsed;
149 UserTime -= TR.UserTime;
150 SystemTime -= TR.SystemTime;
151 MemUsed -= TR.MemUsed;
152 PeakMemBase = TR.MemUsed;
155 void Timer::stopTimer() {
156 TimeRecord TR = getTimeRecord(false);
157 Elapsed += TR.Elapsed;
158 UserTime += TR.UserTime;
159 SystemTime += TR.SystemTime;
160 MemUsed += TR.MemUsed;
162 if (ActiveTimers->back() == this) {
163 ActiveTimers->pop_back();
165 std::vector<Timer*>::iterator I =
166 std::find(ActiveTimers->begin(), ActiveTimers->end(), this);
167 assert(I != ActiveTimers->end() && "stop but no startTimer?");
168 ActiveTimers->erase(I);
172 void Timer::sum(const Timer &T) {
173 Elapsed += T.Elapsed;
174 UserTime += T.UserTime;
175 SystemTime += T.SystemTime;
176 MemUsed += T.MemUsed;
177 PeakMem += T.PeakMem;
180 /// addPeakMemoryMeasurement - This method should be called whenever memory
181 /// usage needs to be checked. It adds a peak memory measurement to the
182 /// currently active timers, which will be printed when the timer group prints
184 void Timer::addPeakMemoryMeasurement() {
185 size_t MemUsed = getMemUsage();
187 for (std::vector<Timer*>::iterator I = ActiveTimers->begin(),
188 E = ActiveTimers->end(); I != E; ++I)
189 (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase);
192 //===----------------------------------------------------------------------===//
193 // NamedRegionTimer Implementation
194 //===----------------------------------------------------------------------===//
198 typedef std::map<std::string, Timer> Name2Timer;
199 typedef std::map<std::string, std::pair<TimerGroup, Name2Timer> > Name2Pair;
203 static ManagedStatic<Name2Timer> NamedTimers;
205 static ManagedStatic<Name2Pair> NamedGroupedTimers;
207 static Timer &getNamedRegionTimer(const std::string &Name) {
208 Name2Timer::iterator I = NamedTimers->find(Name);
209 if (I != NamedTimers->end())
212 return NamedTimers->insert(I, std::make_pair(Name, Timer(Name)))->second;
215 static Timer &getNamedRegionTimer(const std::string &Name,
216 const std::string &GroupName) {
218 Name2Pair::iterator I = NamedGroupedTimers->find(GroupName);
219 if (I == NamedGroupedTimers->end()) {
220 TimerGroup TG(GroupName);
221 std::pair<TimerGroup, Name2Timer> Pair(TG, Name2Timer());
222 I = NamedGroupedTimers->insert(I, std::make_pair(GroupName, Pair));
225 Name2Timer::iterator J = I->second.second.find(Name);
226 if (J == I->second.second.end())
227 J = I->second.second.insert(J,
235 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
236 : TimeRegion(getNamedRegionTimer(Name)) {}
238 NamedRegionTimer::NamedRegionTimer(const std::string &Name,
239 const std::string &GroupName)
240 : TimeRegion(getNamedRegionTimer(Name, GroupName)) {}
242 //===----------------------------------------------------------------------===//
243 // TimerGroup Implementation
244 //===----------------------------------------------------------------------===//
246 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
247 // TotalWidth size, and B is the AfterDec size.
249 static void printAlignedFP(double Val, unsigned AfterDec, unsigned TotalWidth,
251 assert(TotalWidth >= AfterDec+1 && "Bad FP Format!");
252 OS.width(TotalWidth-AfterDec-1);
253 char OldFill = OS.fill();
255 OS << (int)Val; // Integer part;
259 unsigned ResultFieldSize = 1;
260 while (AfterDec--) ResultFieldSize *= 10;
261 OS << (int)(Val*ResultFieldSize) % ResultFieldSize;
265 static void printVal(double Val, double Total, std::ostream &OS) {
266 if (Total < 1e-7) // Avoid dividing by zero...
270 printAlignedFP(Val, 4, 7, OS);
272 printAlignedFP(Val*100/Total, 1, 5, OS);
277 void Timer::print(const Timer &Total, std::ostream &OS) {
279 printVal(UserTime / 1000000.0, Total.UserTime / 1000000.0, OS);
280 if (Total.SystemTime)
281 printVal(SystemTime / 1000000.0, Total.SystemTime / 1000000.0, OS);
282 if (Total.getProcessTime())
283 printVal(getProcessTime() / 1000000.0,
284 Total.getProcessTime() / 1000000.0, OS);
285 printVal(Elapsed / 1000000.0, Total.Elapsed / 1000000.0, OS);
291 OS << MemUsed << " ";
296 OS << PeakMem << " ";
302 Started = false; // Once printed, don't print again
305 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
307 llvm::GetLibSupportInfoOutputFile() {
308 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
309 if (LibSupportInfoOutputFilename.empty())
310 return cerr.stream();
311 if (LibSupportInfoOutputFilename == "-")
312 return cout.stream();
314 std::ostream *Result = new std::ofstream(LibSupportInfoOutputFilename.c_str(),
316 if (!Result->good()) {
317 cerr << "Error opening info-output-file '"
318 << LibSupportInfoOutputFilename << " for appending!\n";
320 return cerr.stream();
326 void TimerGroup::removeTimer() {
327 if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report...
328 // Sort the timers in descending order by amount of time taken...
329 std::sort(TimersToPrint.begin(), TimersToPrint.end(),
330 std::greater<Timer>());
332 // Figure out how many spaces to indent TimerGroup name...
333 unsigned Padding = (80-Name.length())/2;
334 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
336 std::ostream *OutStream = GetLibSupportInfoOutputFile();
339 { // Scope to contain Total timer... don't allow total timer to drop us to
341 Timer Total("TOTAL");
343 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
344 Total.sum(TimersToPrint[i]);
346 // Print out timing header...
347 *OutStream << "===" << std::string(73, '-') << "===\n"
348 << std::string(Padding, ' ') << Name << "\n"
349 << "===" << std::string(73, '-')
352 // If this is not an collection of ungrouped times, print the total time.
353 // Ungrouped timers don't really make sense to add up. We still print the
354 // TOTAL line to make the percentages make sense.
355 if (this != DefaultTimerGroup) {
356 *OutStream << " Total Execution Time: ";
358 printAlignedFP(Total.getProcessTime() / 1000000.0, 4, 5, *OutStream);
359 *OutStream << " seconds (";
360 printAlignedFP(Total.getWallTime() / 1000000.0, 4, 5, *OutStream);
361 *OutStream << " wall clock)\n";
365 if (Total.UserTime / 1000000.0)
366 *OutStream << " ---User Time---";
367 if (Total.SystemTime / 1000000.0)
368 *OutStream << " --System Time--";
369 if (Total.getProcessTime() / 1000000.0)
370 *OutStream << " --User+System--";
371 *OutStream << " ---Wall Time---";
372 if (Total.getMemUsed() / 1000000.0)
373 *OutStream << " ---Mem---";
374 if (Total.getPeakMem() / 1000000.0)
375 *OutStream << " -PeakMem-";
376 *OutStream << " --- Name ---\n";
378 // Loop through all of the timing data, printing it out...
379 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
380 TimersToPrint[i].print(Total, *OutStream);
382 Total.print(Total, *OutStream);
383 *OutStream << std::endl; // Flush output
387 TimersToPrint.clear();
389 if (OutStream != cerr.stream() && OutStream != cout.stream())
390 delete OutStream; // Close the file...