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/System/Process.h"
24 // GetLibSupportInfoOutputFile - Return a file stream to print our output on.
25 namespace llvm { extern std::ostream *GetLibSupportInfoOutputFile(); }
27 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
28 // of constructor/destructor ordering being unspecified by C++. Basically the
29 // problem is that a Statistic<> object gets destroyed, which ends up calling
30 // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
31 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
32 // would get destroyed before the Statistic, causing havoc to ensue. We "fix"
33 // this by creating the string the first time it is needed and never destroying
35 static std::string &getLibSupportInfoOutputFilename() {
36 static std::string *LibSupportInfoOutputFilename = new std::string();
37 return *LibSupportInfoOutputFilename;
42 TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
43 "tracking (this may be slow)"),
46 cl::opt<std::string, true>
47 InfoOutputFilename("info-output-file", cl::value_desc("filename"),
48 cl::desc("File to append -stats and -timer output to"),
49 cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
52 static TimerGroup *DefaultTimerGroup = 0;
53 static TimerGroup *getDefaultTimerGroup() {
54 if (DefaultTimerGroup) return DefaultTimerGroup;
55 return DefaultTimerGroup = new TimerGroup("Miscellaneous Ungrouped Timers");
58 Timer::Timer(const std::string &N)
59 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
60 Started(false), TG(getDefaultTimerGroup()) {
64 Timer::Timer(const std::string &N, TimerGroup &tg)
65 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
66 Started(false), TG(&tg) {
70 Timer::Timer(const Timer &T) {
72 if (TG) TG->addTimer();
77 // Copy ctor, initialize with no TG member.
78 Timer::Timer(bool, const Timer &T) {
79 TG = T.TG; // Avoid assertion in operator=
80 operator=(T); // Copy contents
89 TG->addTimerToPrint(*this);
95 static inline size_t getMemUsage() {
97 return sys::Process::GetMallocUsage();
102 double Elapsed, UserTime, SystemTime;
106 static TimeRecord getTimeRecord(bool Start) {
109 sys::TimeValue now(0,0);
110 sys::TimeValue user(0,0);
111 sys::TimeValue sys(0,0);
115 MemUsed = getMemUsage();
116 sys::Process::GetTimeUsage(now,user,sys);
118 sys::Process::GetTimeUsage(now,user,sys);
119 MemUsed = getMemUsage();
122 Result.Elapsed = now.seconds() + now.microseconds() / 1000000.0;
123 Result.UserTime = user.seconds() + user.microseconds() / 1000000.0;
124 Result.SystemTime = sys.seconds() + sys.microseconds() / 1000000.0;
125 Result.MemUsed = MemUsed;
130 static std::vector<Timer*> ActiveTimers;
132 void Timer::startTimer() {
134 TimeRecord TR = getTimeRecord(true);
135 Elapsed -= TR.Elapsed;
136 UserTime -= TR.UserTime;
137 SystemTime -= TR.SystemTime;
138 MemUsed -= TR.MemUsed;
139 PeakMemBase = TR.MemUsed;
140 ActiveTimers.push_back(this);
143 void Timer::stopTimer() {
144 TimeRecord TR = getTimeRecord(false);
145 Elapsed += TR.Elapsed;
146 UserTime += TR.UserTime;
147 SystemTime += TR.SystemTime;
148 MemUsed += TR.MemUsed;
150 if (ActiveTimers.back() == this) {
151 ActiveTimers.pop_back();
153 std::vector<Timer*>::iterator I =
154 std::find(ActiveTimers.begin(), ActiveTimers.end(), this);
155 assert(I != ActiveTimers.end() && "stop but no startTimer?");
156 ActiveTimers.erase(I);
160 void Timer::sum(const Timer &T) {
161 Elapsed += T.Elapsed;
162 UserTime += T.UserTime;
163 SystemTime += T.SystemTime;
164 MemUsed += T.MemUsed;
165 PeakMem += T.PeakMem;
168 /// addPeakMemoryMeasurement - This method should be called whenever memory
169 /// usage needs to be checked. It adds a peak memory measurement to the
170 /// currently active timers, which will be printed when the timer group prints
172 void Timer::addPeakMemoryMeasurement() {
173 size_t MemUsed = getMemUsage();
175 for (std::vector<Timer*>::iterator I = ActiveTimers.begin(),
176 E = ActiveTimers.end(); I != E; ++I)
177 (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase);
180 //===----------------------------------------------------------------------===//
181 // NamedRegionTimer Implementation
182 //===----------------------------------------------------------------------===//
184 static Timer &getNamedRegionTimer(const std::string &Name) {
185 static std::map<std::string, Timer> NamedTimers;
187 std::map<std::string, Timer>::iterator I = NamedTimers.lower_bound(Name);
188 if (I != NamedTimers.end() && I->first == Name)
191 return NamedTimers.insert(I, std::make_pair(Name, Timer(Name)))->second;
194 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
195 : TimeRegion(getNamedRegionTimer(Name)) {}
198 //===----------------------------------------------------------------------===//
199 // TimerGroup Implementation
200 //===----------------------------------------------------------------------===//
202 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
203 // TotalWidth size, and B is the AfterDec size.
205 static void printAlignedFP(double Val, unsigned AfterDec, unsigned TotalWidth,
207 assert(TotalWidth >= AfterDec+1 && "Bad FP Format!");
208 OS.width(TotalWidth-AfterDec-1);
209 char OldFill = OS.fill();
211 OS << (int)Val; // Integer part;
215 unsigned ResultFieldSize = 1;
216 while (AfterDec--) ResultFieldSize *= 10;
217 OS << (int)(Val*ResultFieldSize) % ResultFieldSize;
221 static void printVal(double Val, double Total, std::ostream &OS) {
222 if (Total < 1e-7) // Avoid dividing by zero...
226 printAlignedFP(Val, 4, 7, OS);
228 printAlignedFP(Val*100/Total, 1, 5, OS);
233 void Timer::print(const Timer &Total, std::ostream &OS) {
235 printVal(UserTime, Total.UserTime, OS);
236 if (Total.SystemTime)
237 printVal(SystemTime, Total.SystemTime, OS);
238 if (Total.getProcessTime())
239 printVal(getProcessTime(), Total.getProcessTime(), OS);
240 printVal(Elapsed, Total.Elapsed, OS);
246 OS << MemUsed << " ";
251 OS << PeakMem << " ";
257 Started = false; // Once printed, don't print again
260 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
262 llvm::GetLibSupportInfoOutputFile() {
263 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
264 if (LibSupportInfoOutputFilename.empty())
266 if (LibSupportInfoOutputFilename == "-")
269 std::ostream *Result = new std::ofstream(LibSupportInfoOutputFilename.c_str(),
271 if (!Result->good()) {
272 std::cerr << "Error opening info-output-file '"
273 << LibSupportInfoOutputFilename << " for appending!\n";
281 void TimerGroup::removeTimer() {
282 if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report...
283 // Sort the timers in descending order by amount of time taken...
284 std::sort(TimersToPrint.begin(), TimersToPrint.end(),
285 std::greater<Timer>());
287 // Figure out how many spaces to indent TimerGroup name...
288 unsigned Padding = (80-Name.length())/2;
289 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
291 std::ostream *OutStream = GetLibSupportInfoOutputFile();
294 { // Scope to contain Total timer... don't allow total timer to drop us to
296 Timer Total("TOTAL");
298 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
299 Total.sum(TimersToPrint[i]);
301 // Print out timing header...
302 *OutStream << "===" << std::string(73, '-') << "===\n"
303 << std::string(Padding, ' ') << Name << "\n"
304 << "===" << std::string(73, '-')
307 // If this is not an collection of ungrouped times, print the total time.
308 // Ungrouped timers don't really make sense to add up. We still print the
309 // TOTAL line to make the percentages make sense.
310 if (this != DefaultTimerGroup) {
311 *OutStream << " Total Execution Time: ";
313 printAlignedFP(Total.getProcessTime(), 4, 5, *OutStream);
314 *OutStream << " seconds (";
315 printAlignedFP(Total.getWallTime(), 4, 5, *OutStream);
316 *OutStream << " wall clock)\n";
321 *OutStream << " ---User Time---";
322 if (Total.SystemTime)
323 *OutStream << " --System Time--";
324 if (Total.getProcessTime())
325 *OutStream << " --User+System--";
326 *OutStream << " ---Wall Time---";
327 if (Total.getMemUsed())
328 *OutStream << " ---Mem---";
329 if (Total.getPeakMem())
330 *OutStream << " -PeakMem-";
331 *OutStream << " --- Name ---\n";
333 // Loop through all of the timing data, printing it out...
334 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
335 TimersToPrint[i].print(Total, *OutStream);
337 Total.print(Total, *OutStream);
338 *OutStream << std::endl; // Flush output
342 TimersToPrint.clear();
344 if (OutStream != &std::cerr && OutStream != &std::cout)
345 delete OutStream; // Close the file...
348 // Delete default timer group!
349 if (NumTimers == 0 && this == DefaultTimerGroup) {
350 delete DefaultTimerGroup;
351 DefaultTimerGroup = 0;