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 "Support/Timer.h"
15 #include "Support/CommandLine.h"
16 #include "Config/sys/resource.h"
17 #include "Config/sys/time.h"
18 #include "Config/unistd.h"
19 #include "Config/malloc.h"
26 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
27 // of constructor/destructor ordering being unspecified by C++. Basically the
28 // problem is that a Statistic<> object gets destroyed, which ends up calling
29 // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
30 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
31 // would get destroyed before the Statistic, causing havoc to ensue. We "fix"
32 // this by creating the string the first time it is needed and never destroying
34 static std::string &getLibSupportInfoOutputFilename() {
35 static std::string *LibSupportInfoOutputFilename = new std::string();
36 return *LibSupportInfoOutputFilename;
42 TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
43 "tracking (this may be slow)"),
47 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 if (DefaultTimerGroup) return DefaultTimerGroup;
56 return DefaultTimerGroup = new TimerGroup("Miscellaneous Ungrouped Timers");
59 Timer::Timer(const std::string &N)
60 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
61 Started(false), TG(getDefaultTimerGroup()) {
65 Timer::Timer(const std::string &N, TimerGroup &tg)
66 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
67 Started(false), TG(&tg) {
71 Timer::Timer(const Timer &T) {
73 if (TG) TG->addTimer();
78 // Copy ctor, initialize with no TG member.
79 Timer::Timer(bool, const Timer &T) {
80 TG = T.TG; // Avoid assertion in operator=
81 operator=(T); // Copy contents
90 TG->addTimerToPrint(*this);
96 static long getMemUsage() {
99 struct mallinfo MI = mallinfo();
100 return MI.uordblks/*+MI.hblkhd*/;
107 double Elapsed, UserTime, SystemTime;
111 static TimeRecord getTimeRecord(bool Start) {
116 MemUsed = getMemUsage();
117 if (getrusage(RUSAGE_SELF, &RU))
118 perror("getrusage call failed: -time-passes info incorrect!");
123 MemUsed = getMemUsage();
124 if (getrusage(RUSAGE_SELF, &RU))
125 perror("getrusage call failed: -time-passes info incorrect!");
129 Result.Elapsed = T.tv_sec + T.tv_usec/1000000.0;
130 Result.UserTime = RU.ru_utime.tv_sec + RU.ru_utime.tv_usec/1000000.0;
131 Result.SystemTime = RU.ru_stime.tv_sec + RU.ru_stime.tv_usec/1000000.0;
132 Result.MemUsed = MemUsed;
137 static std::vector<Timer*> ActiveTimers;
139 void Timer::startTimer() {
141 TimeRecord TR = getTimeRecord(true);
142 Elapsed -= TR.Elapsed;
143 UserTime -= TR.UserTime;
144 SystemTime -= TR.SystemTime;
145 MemUsed -= TR.MemUsed;
146 PeakMemBase = TR.MemUsed;
147 ActiveTimers.push_back(this);
150 void Timer::stopTimer() {
151 TimeRecord TR = getTimeRecord(false);
152 Elapsed += TR.Elapsed;
153 UserTime += TR.UserTime;
154 SystemTime += TR.SystemTime;
155 MemUsed += TR.MemUsed;
157 if (ActiveTimers.back() == this) {
158 ActiveTimers.pop_back();
160 std::vector<Timer*>::iterator I =
161 std::find(ActiveTimers.begin(), ActiveTimers.end(), this);
162 assert(I != ActiveTimers.end() && "stop but no startTimer?");
163 ActiveTimers.erase(I);
167 void Timer::sum(const Timer &T) {
168 Elapsed += T.Elapsed;
169 UserTime += T.UserTime;
170 SystemTime += T.SystemTime;
171 MemUsed += T.MemUsed;
172 PeakMem += T.PeakMem;
175 /// addPeakMemoryMeasurement - This method should be called whenever memory
176 /// usage needs to be checked. It adds a peak memory measurement to the
177 /// currently active timers, which will be printed when the timer group prints
179 void Timer::addPeakMemoryMeasurement() {
180 long MemUsed = getMemUsage();
182 for (std::vector<Timer*>::iterator I = ActiveTimers.begin(),
183 E = ActiveTimers.end(); I != E; ++I)
184 (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase);
187 //===----------------------------------------------------------------------===//
188 // NamedRegionTimer Implementation
189 //===----------------------------------------------------------------------===//
191 static Timer &getNamedRegionTimer(const std::string &Name) {
192 static std::map<std::string, Timer> NamedTimers;
194 std::map<std::string, Timer>::iterator I = NamedTimers.lower_bound(Name);
195 if (I != NamedTimers.end() && I->first == Name)
198 return NamedTimers.insert(I, std::make_pair(Name, Timer(Name)))->second;
201 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
202 : TimeRegion(getNamedRegionTimer(Name)) {}
205 //===----------------------------------------------------------------------===//
206 // TimerGroup Implementation
207 //===----------------------------------------------------------------------===//
209 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
210 // TotalWidth size, and B is the AfterDec size.
212 static void printAlignedFP(double Val, unsigned AfterDec, unsigned TotalWidth,
214 assert(TotalWidth >= AfterDec+1 && "Bad FP Format!");
215 OS.width(TotalWidth-AfterDec-1);
216 char OldFill = OS.fill();
218 OS << (int)Val; // Integer part;
222 unsigned ResultFieldSize = 1;
223 while (AfterDec--) ResultFieldSize *= 10;
224 OS << (int)(Val*ResultFieldSize) % ResultFieldSize;
228 static void printVal(double Val, double Total, std::ostream &OS) {
229 if (Total < 1e-7) // Avoid dividing by zero...
233 printAlignedFP(Val, 4, 7, OS);
235 printAlignedFP(Val*100/Total, 1, 5, OS);
240 void Timer::print(const Timer &Total, std::ostream &OS) {
242 printVal(UserTime, Total.UserTime, OS);
243 if (Total.SystemTime)
244 printVal(SystemTime, Total.SystemTime, OS);
245 if (Total.getProcessTime())
246 printVal(getProcessTime(), Total.getProcessTime(), OS);
247 printVal(Elapsed, Total.Elapsed, OS);
253 OS << MemUsed << " ";
258 OS << PeakMem << " ";
264 Started = false; // Once printed, don't print again
267 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
268 std::ostream *GetLibSupportInfoOutputFile() {
269 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
270 if (LibSupportInfoOutputFilename.empty())
272 if (LibSupportInfoOutputFilename == "-")
275 std::ostream *Result = new std::ofstream(LibSupportInfoOutputFilename.c_str(),
277 if (!Result->good()) {
278 std::cerr << "Error opening info-output-file '"
279 << LibSupportInfoOutputFilename << " for appending!\n";
287 void TimerGroup::removeTimer() {
288 if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report...
289 // Sort the timers in descending order by amount of time taken...
290 std::sort(TimersToPrint.begin(), TimersToPrint.end(),
291 std::greater<Timer>());
293 // Figure out how many spaces to indent TimerGroup name...
294 unsigned Padding = (80-Name.length())/2;
295 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
297 std::ostream *OutStream = GetLibSupportInfoOutputFile();
300 { // Scope to contain Total timer... don't allow total timer to drop us to
302 Timer Total("TOTAL");
304 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
305 Total.sum(TimersToPrint[i]);
307 // Print out timing header...
308 *OutStream << "===" << std::string(73, '-') << "===\n"
309 << std::string(Padding, ' ') << Name << "\n"
310 << "===" << std::string(73, '-')
311 << "===\n 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\n";
319 *OutStream << " ---User Time---";
320 if (Total.SystemTime)
321 *OutStream << " --System Time--";
322 if (Total.getProcessTime())
323 *OutStream << " --User+System--";
324 *OutStream << " ---Wall Time---";
325 if (Total.getMemUsed())
326 *OutStream << " ---Mem---";
327 if (Total.getPeakMem())
328 *OutStream << " -PeakMem-";
329 *OutStream << " --- Name ---\n";
331 // Loop through all of the timing data, printing it out...
332 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
333 TimersToPrint[i].print(Total, *OutStream);
335 Total.print(Total, *OutStream);
336 *OutStream << std::endl; // Flush output
340 TimersToPrint.clear();
342 if (OutStream != &std::cerr && OutStream != &std::cout)
343 delete OutStream; // Close the file...
346 // Delete default timer group!
347 if (NumTimers == 0 && this == DefaultTimerGroup) {
348 delete DefaultTimerGroup;
349 DefaultTimerGroup = 0;