1 //===-- Timer.cpp - Interval Timing Support -------------------------------===//
3 // Interval Timing implementation.
5 //===----------------------------------------------------------------------===//
7 #include "Support/Timer.h"
8 #include "Support/CommandLine.h"
9 #include "Config/sys/resource.h"
10 #include "Config/sys/time.h"
11 #include "Config/unistd.h"
12 #include "Config/malloc.h"
19 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
20 // of constructor/destructor ordering being unspecified by C++. Basically the
21 // problem is that a Statistic<> object gets destroyed, which ends up calling
22 // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
23 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
24 // would get destroyed before the Statistic, causing havoc to ensue. We "fix"
25 // this by creating the string the first time it is needed and never destroying
27 static std::string &getLibSupportInfoOutputFilename() {
28 static std::string *LibSupportInfoOutputFilename = new std::string();
29 return *LibSupportInfoOutputFilename;
35 TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
36 "tracking (this may be slow)"),
40 cl::opt<std::string, true>
41 InfoOutputFilename("info-output-file", cl::value_desc("filename"),
42 cl::desc("File to append -stats and -timer output to"),
43 cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
46 static TimerGroup *DefaultTimerGroup = 0;
47 static TimerGroup *getDefaultTimerGroup() {
48 if (DefaultTimerGroup) return DefaultTimerGroup;
49 return DefaultTimerGroup = new TimerGroup("Miscellaneous Ungrouped Timers");
52 Timer::Timer(const std::string &N)
53 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
54 Started(false), TG(getDefaultTimerGroup()) {
58 Timer::Timer(const std::string &N, TimerGroup &tg)
59 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
60 Started(false), TG(&tg) {
64 Timer::Timer(const Timer &T) {
66 if (TG) TG->addTimer();
71 // Copy ctor, initialize with no TG member.
72 Timer::Timer(bool, const Timer &T) {
73 TG = T.TG; // Avoid assertion in operator=
74 operator=(T); // Copy contents
83 TG->addTimerToPrint(*this);
89 static long getMemUsage() {
92 struct mallinfo MI = mallinfo();
93 return MI.uordblks/*+MI.hblkhd*/;
100 double Elapsed, UserTime, SystemTime;
104 static TimeRecord getTimeRecord(bool Start) {
109 MemUsed = getMemUsage();
110 if (getrusage(RUSAGE_SELF, &RU))
111 perror("getrusage call failed: -time-passes info incorrect!");
116 MemUsed = getMemUsage();
117 if (getrusage(RUSAGE_SELF, &RU))
118 perror("getrusage call failed: -time-passes info incorrect!");
122 Result.Elapsed = T.tv_sec + T.tv_usec/1000000.0;
123 Result.UserTime = RU.ru_utime.tv_sec + RU.ru_utime.tv_usec/1000000.0;
124 Result.SystemTime = RU.ru_stime.tv_sec + RU.ru_stime.tv_usec/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 long 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...
261 std::ostream *GetLibSupportInfoOutputFile() {
262 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
263 if (LibSupportInfoOutputFilename.empty())
265 if (LibSupportInfoOutputFilename == "-")
268 std::ostream *Result = new std::ofstream(LibSupportInfoOutputFilename.c_str(),
270 if (!Result->good()) {
271 std::cerr << "Error opening info-output-file '"
272 << LibSupportInfoOutputFilename << " for appending!\n";
280 void TimerGroup::removeTimer() {
281 if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report...
282 // Sort the timers in descending order by amount of time taken...
283 std::sort(TimersToPrint.begin(), TimersToPrint.end(),
284 std::greater<Timer>());
286 // Figure out how many spaces to indent TimerGroup name...
287 unsigned Padding = (80-Name.length())/2;
288 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
290 std::ostream *OutStream = GetLibSupportInfoOutputFile();
293 { // Scope to contain Total timer... don't allow total timer to drop us to
295 Timer Total("TOTAL");
297 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
298 Total.sum(TimersToPrint[i]);
300 // Print out timing header...
301 *OutStream << "===" << std::string(73, '-') << "===\n"
302 << std::string(Padding, ' ') << Name << "\n"
303 << "===" << std::string(73, '-')
304 << "===\n Total Execution Time: ";
306 printAlignedFP(Total.getProcessTime(), 4, 5, *OutStream);
307 *OutStream << " seconds (";
308 printAlignedFP(Total.getWallTime(), 4, 5, *OutStream);
309 *OutStream << " wall clock)\n\n";
312 *OutStream << " ---User Time---";
313 if (Total.SystemTime)
314 *OutStream << " --System Time--";
315 if (Total.getProcessTime())
316 *OutStream << " --User+System--";
317 *OutStream << " ---Wall Time---";
318 if (Total.getMemUsed())
319 *OutStream << " ---Mem---";
320 if (Total.getPeakMem())
321 *OutStream << " -PeakMem-";
322 *OutStream << " --- Name ---\n";
324 // Loop through all of the timing data, printing it out...
325 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
326 TimersToPrint[i].print(Total, *OutStream);
328 Total.print(Total, *OutStream);
329 *OutStream << std::endl; // Flush output
333 TimersToPrint.clear();
335 if (OutStream != &std::cerr && OutStream != &std::cout)
336 delete OutStream; // Close the file...
339 // Delete default timer group!
340 if (NumTimers == 0 && this == DefaultTimerGroup) {
341 delete DefaultTimerGroup;
342 DefaultTimerGroup = 0;