1 //===-- Timer.cpp - Interval Timing Support -------------------------------===//
3 // Interval Timing implementation.
5 //===----------------------------------------------------------------------===//
7 #include "Support/Timer.h"
8 #include "Support/CommandLine.h"
10 #include "Config/sys/resource.h"
11 #include "Config/sys/time.h"
12 #include "Config/unistd.h"
13 #include "Config/malloc.h"
14 #include "Config/stdio.h"
21 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
22 // of constructor/destructor ordering being unspecified by C++. Basically the
23 // problem is that a Statistic<> object gets destroyed, which ends up calling
24 // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
25 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
26 // would get destroyed before the Statistic, causing havoc to ensue. We "fix"
27 // this by creating the string the first time it is needed and never destroying
29 static std::string &getLibSupportInfoOutputFilename() {
30 static std::string *LibSupportInfoOutputFilename = new std::string();
31 return *LibSupportInfoOutputFilename;
37 TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
38 "tracking (this may be slow)"),
42 cl::opt<std::string, true>
43 InfoOutputFilename("info-output-file", cl::value_desc("filename"),
44 cl::desc("File to append -stats and -timer output to"),
45 cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
48 static TimerGroup *DefaultTimerGroup = 0;
49 static TimerGroup *getDefaultTimerGroup() {
50 if (DefaultTimerGroup) return DefaultTimerGroup;
51 return DefaultTimerGroup = new TimerGroup("Miscellaneous Ungrouped Timers");
54 Timer::Timer(const std::string &N)
55 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
56 Started(false), TG(getDefaultTimerGroup()) {
60 Timer::Timer(const std::string &N, TimerGroup &tg)
61 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
62 Started(false), TG(&tg) {
66 Timer::Timer(const Timer &T) {
68 if (TG) TG->addTimer();
73 // Copy ctor, initialize with no TG member.
74 Timer::Timer(bool, const Timer &T) {
75 TG = T.TG; // Avoid assertion in operator=
76 operator=(T); // Copy contents
85 TG->addTimerToPrint(*this);
91 static long getMemUsage() {
94 struct mallinfo MI = mallinfo();
95 return MI.uordblks/*+MI.hblkhd*/;
102 double Elapsed, UserTime, SystemTime;
106 static TimeRecord getTimeRecord(bool Start) {
111 MemUsed = getMemUsage();
112 if (getrusage(RUSAGE_SELF, &RU))
113 perror("getrusage call failed: -time-passes info incorrect!");
118 MemUsed = getMemUsage();
119 if (getrusage(RUSAGE_SELF, &RU))
120 perror("getrusage call failed: -time-passes info incorrect!");
124 Result.Elapsed = T.tv_sec + T.tv_usec/1000000.0;
125 Result.UserTime = RU.ru_utime.tv_sec + RU.ru_utime.tv_usec/1000000.0;
126 Result.SystemTime = RU.ru_stime.tv_sec + RU.ru_stime.tv_usec/1000000.0;
127 Result.MemUsed = MemUsed;
132 static std::vector<Timer*> ActiveTimers;
134 void Timer::startTimer() {
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;
142 ActiveTimers.push_back(this);
145 void Timer::stopTimer() {
146 TimeRecord TR = getTimeRecord(false);
147 Elapsed += TR.Elapsed;
148 UserTime += TR.UserTime;
149 SystemTime += TR.SystemTime;
150 MemUsed += TR.MemUsed;
152 if (ActiveTimers.back() == this) {
153 ActiveTimers.pop_back();
155 std::vector<Timer*>::iterator I =
156 std::find(ActiveTimers.begin(), ActiveTimers.end(), this);
157 assert(I != ActiveTimers.end() && "stop but no startTimer?");
158 ActiveTimers.erase(I);
162 void Timer::sum(const Timer &T) {
163 Elapsed += T.Elapsed;
164 UserTime += T.UserTime;
165 SystemTime += T.SystemTime;
166 MemUsed += T.MemUsed;
167 PeakMem += T.PeakMem;
170 /// addPeakMemoryMeasurement - This method should be called whenever memory
171 /// usage needs to be checked. It adds a peak memory measurement to the
172 /// currently active timers, which will be printed when the timer group prints
174 void Timer::addPeakMemoryMeasurement() {
175 long MemUsed = getMemUsage();
177 for (std::vector<Timer*>::iterator I = ActiveTimers.begin(),
178 E = ActiveTimers.end(); I != E; ++I)
179 (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase);
182 //===----------------------------------------------------------------------===//
183 // NamedRegionTimer Implementation
184 //===----------------------------------------------------------------------===//
186 static Timer &getNamedRegionTimer(const std::string &Name) {
187 static std::map<std::string, Timer> NamedTimers;
189 std::map<std::string, Timer>::iterator I = NamedTimers.lower_bound(Name);
190 if (I != NamedTimers.end() && I->first == Name)
193 return NamedTimers.insert(I, std::make_pair(Name, Timer(Name)))->second;
196 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
197 : TimeRegion(getNamedRegionTimer(Name)) {}
200 //===----------------------------------------------------------------------===//
201 // TimerGroup Implementation
202 //===----------------------------------------------------------------------===//
204 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
205 // TotalWidth size, and B is the AfterDec size.
207 static void printAlignedFP(double Val, unsigned AfterDec, unsigned TotalWidth,
209 assert(TotalWidth >= AfterDec+1 && "Bad FP Format!");
210 OS.width(TotalWidth-AfterDec-1);
211 char OldFill = OS.fill();
213 OS << (int)Val; // Integer part;
217 unsigned ResultFieldSize = 1;
218 while (AfterDec--) ResultFieldSize *= 10;
219 OS << (int)(Val*ResultFieldSize) % ResultFieldSize;
223 static void printVal(double Val, double Total, std::ostream &OS) {
224 if (Total < 1e-7) // Avoid dividing by zero...
228 printAlignedFP(Val, 4, 7, OS);
230 printAlignedFP(Val*100/Total, 1, 5, OS);
235 void Timer::print(const Timer &Total, std::ostream &OS) {
237 printVal(UserTime, Total.UserTime, OS);
238 if (Total.SystemTime)
239 printVal(SystemTime, Total.SystemTime, OS);
240 if (Total.getProcessTime())
241 printVal(getProcessTime(), Total.getProcessTime(), OS);
242 printVal(Elapsed, Total.Elapsed, OS);
248 OS << MemUsed << " ";
253 OS << PeakMem << " ";
259 Started = false; // Once printed, don't print again
262 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
263 std::ostream *GetLibSupportInfoOutputFile() {
264 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
265 if (LibSupportInfoOutputFilename.empty())
267 if (LibSupportInfoOutputFilename == "-")
270 std::ostream *Result = new std::ofstream(LibSupportInfoOutputFilename.c_str(),
272 if (!Result->good()) {
273 std::cerr << "Error opening info-output-file '"
274 << LibSupportInfoOutputFilename << " for appending!\n";
282 void TimerGroup::removeTimer() {
283 if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report...
284 // Sort the timers in descending order by amount of time taken...
285 std::sort(TimersToPrint.begin(), TimersToPrint.end(),
286 std::greater<Timer>());
288 // Figure out how many spaces to indent TimerGroup name...
289 unsigned Padding = (80-Name.length())/2;
290 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
292 std::ostream *OutStream = GetLibSupportInfoOutputFile();
295 { // Scope to contain Total timer... don't allow total timer to drop us to
297 Timer Total("TOTAL");
299 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
300 Total.sum(TimersToPrint[i]);
302 // Print out timing header...
303 *OutStream << "===" << std::string(73, '-') << "===\n"
304 << std::string(Padding, ' ') << Name << "\n"
305 << "===" << std::string(73, '-')
306 << "===\n Total Execution Time: ";
308 printAlignedFP(Total.getProcessTime(), 4, 5, *OutStream);
309 *OutStream << " seconds (";
310 printAlignedFP(Total.getWallTime(), 4, 5, *OutStream);
311 *OutStream << " wall clock)\n\n";
314 *OutStream << " ---User Time---";
315 if (Total.SystemTime)
316 *OutStream << " --System Time--";
317 if (Total.getProcessTime())
318 *OutStream << " --User+System--";
319 *OutStream << " ---Wall Time---";
320 if (Total.getMemUsed())
321 *OutStream << " ---Mem---";
322 if (Total.getPeakMem())
323 *OutStream << " -PeakMem-";
324 *OutStream << " --- Name ---\n";
326 // Loop through all of the timing data, printing it out...
327 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
328 TimersToPrint[i].print(Total, *OutStream);
330 Total.print(Total, *OutStream);
331 *OutStream << std::endl; // Flush output
335 TimersToPrint.clear();
337 if (OutStream != &std::cerr && OutStream != &std::cout)
338 delete OutStream; // Close the file...
341 // Delete default timer group!
342 if (NumTimers == 0 && this == DefaultTimerGroup) {
343 delete DefaultTimerGroup;
344 DefaultTimerGroup = 0;