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"
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 std::string &getLibSupportInfoOutputFilename() {
37 static std::string *LibSupportInfoOutputFilename = new std::string();
38 return *LibSupportInfoOutputFilename;
44 TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
45 "tracking (this may be slow)"),
49 cl::opt<std::string, true>
50 InfoOutputFilename("info-output-file", cl::value_desc("filename"),
51 cl::desc("File to append -stats and -timer output to"),
52 cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
55 static TimerGroup *DefaultTimerGroup = 0;
56 static TimerGroup *getDefaultTimerGroup() {
57 if (DefaultTimerGroup) return DefaultTimerGroup;
58 return DefaultTimerGroup = new TimerGroup("Miscellaneous Ungrouped Timers");
61 Timer::Timer(const std::string &N)
62 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
63 Started(false), TG(getDefaultTimerGroup()) {
67 Timer::Timer(const std::string &N, TimerGroup &tg)
68 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
69 Started(false), TG(&tg) {
73 Timer::Timer(const Timer &T) {
75 if (TG) TG->addTimer();
80 // Copy ctor, initialize with no TG member.
81 Timer::Timer(bool, const Timer &T) {
82 TG = T.TG; // Avoid assertion in operator=
83 operator=(T); // Copy contents
92 TG->addTimerToPrint(*this);
98 static long getMemUsage() {
101 struct mallinfo MI = mallinfo();
102 return MI.uordblks/*+MI.hblkhd*/;
109 double Elapsed, UserTime, SystemTime;
113 static TimeRecord getTimeRecord(bool Start) {
118 MemUsed = getMemUsage();
119 if (getrusage(RUSAGE_SELF, &RU))
120 perror("getrusage call failed: -time-passes info incorrect!");
125 MemUsed = getMemUsage();
126 if (getrusage(RUSAGE_SELF, &RU))
127 perror("getrusage call failed: -time-passes info incorrect!");
131 Result.Elapsed = T.tv_sec + T.tv_usec/1000000.0;
132 Result.UserTime = RU.ru_utime.tv_sec + RU.ru_utime.tv_usec/1000000.0;
133 Result.SystemTime = RU.ru_stime.tv_sec + RU.ru_stime.tv_usec/1000000.0;
134 Result.MemUsed = MemUsed;
139 static std::vector<Timer*> ActiveTimers;
141 void Timer::startTimer() {
143 TimeRecord TR = getTimeRecord(true);
144 Elapsed -= TR.Elapsed;
145 UserTime -= TR.UserTime;
146 SystemTime -= TR.SystemTime;
147 MemUsed -= TR.MemUsed;
148 PeakMemBase = TR.MemUsed;
149 ActiveTimers.push_back(this);
152 void Timer::stopTimer() {
153 TimeRecord TR = getTimeRecord(false);
154 Elapsed += TR.Elapsed;
155 UserTime += TR.UserTime;
156 SystemTime += TR.SystemTime;
157 MemUsed += TR.MemUsed;
159 if (ActiveTimers.back() == this) {
160 ActiveTimers.pop_back();
162 std::vector<Timer*>::iterator I =
163 std::find(ActiveTimers.begin(), ActiveTimers.end(), this);
164 assert(I != ActiveTimers.end() && "stop but no startTimer?");
165 ActiveTimers.erase(I);
169 void Timer::sum(const Timer &T) {
170 Elapsed += T.Elapsed;
171 UserTime += T.UserTime;
172 SystemTime += T.SystemTime;
173 MemUsed += T.MemUsed;
174 PeakMem += T.PeakMem;
177 /// addPeakMemoryMeasurement - This method should be called whenever memory
178 /// usage needs to be checked. It adds a peak memory measurement to the
179 /// currently active timers, which will be printed when the timer group prints
181 void Timer::addPeakMemoryMeasurement() {
182 long MemUsed = getMemUsage();
184 for (std::vector<Timer*>::iterator I = ActiveTimers.begin(),
185 E = ActiveTimers.end(); I != E; ++I)
186 (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase);
189 //===----------------------------------------------------------------------===//
190 // NamedRegionTimer Implementation
191 //===----------------------------------------------------------------------===//
193 static Timer &getNamedRegionTimer(const std::string &Name) {
194 static std::map<std::string, Timer> NamedTimers;
196 std::map<std::string, Timer>::iterator I = NamedTimers.lower_bound(Name);
197 if (I != NamedTimers.end() && I->first == Name)
200 return NamedTimers.insert(I, std::make_pair(Name, Timer(Name)))->second;
203 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
204 : TimeRegion(getNamedRegionTimer(Name)) {}
207 //===----------------------------------------------------------------------===//
208 // TimerGroup Implementation
209 //===----------------------------------------------------------------------===//
211 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
212 // TotalWidth size, and B is the AfterDec size.
214 static void printAlignedFP(double Val, unsigned AfterDec, unsigned TotalWidth,
216 assert(TotalWidth >= AfterDec+1 && "Bad FP Format!");
217 OS.width(TotalWidth-AfterDec-1);
218 char OldFill = OS.fill();
220 OS << (int)Val; // Integer part;
224 unsigned ResultFieldSize = 1;
225 while (AfterDec--) ResultFieldSize *= 10;
226 OS << (int)(Val*ResultFieldSize) % ResultFieldSize;
230 static void printVal(double Val, double Total, std::ostream &OS) {
231 if (Total < 1e-7) // Avoid dividing by zero...
235 printAlignedFP(Val, 4, 7, OS);
237 printAlignedFP(Val*100/Total, 1, 5, OS);
242 void Timer::print(const Timer &Total, std::ostream &OS) {
244 printVal(UserTime, Total.UserTime, OS);
245 if (Total.SystemTime)
246 printVal(SystemTime, Total.SystemTime, OS);
247 if (Total.getProcessTime())
248 printVal(getProcessTime(), Total.getProcessTime(), OS);
249 printVal(Elapsed, Total.Elapsed, OS);
255 OS << MemUsed << " ";
260 OS << PeakMem << " ";
266 Started = false; // Once printed, don't print again
269 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
271 GetLibSupportInfoOutputFile() {
272 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
273 if (LibSupportInfoOutputFilename.empty())
275 if (LibSupportInfoOutputFilename == "-")
278 std::ostream *Result = new std::ofstream(LibSupportInfoOutputFilename.c_str(),
280 if (!Result->good()) {
281 std::cerr << "Error opening info-output-file '"
282 << LibSupportInfoOutputFilename << " for appending!\n";
290 void TimerGroup::removeTimer() {
291 if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report...
292 // Sort the timers in descending order by amount of time taken...
293 std::sort(TimersToPrint.begin(), TimersToPrint.end(),
294 std::greater<Timer>());
296 // Figure out how many spaces to indent TimerGroup name...
297 unsigned Padding = (80-Name.length())/2;
298 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
300 std::ostream *OutStream = GetLibSupportInfoOutputFile();
303 { // Scope to contain Total timer... don't allow total timer to drop us to
305 Timer Total("TOTAL");
307 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
308 Total.sum(TimersToPrint[i]);
310 // Print out timing header...
311 *OutStream << "===" << std::string(73, '-') << "===\n"
312 << std::string(Padding, ' ') << Name << "\n"
313 << "===" << std::string(73, '-')
314 << "===\n Total Execution Time: ";
316 printAlignedFP(Total.getProcessTime(), 4, 5, *OutStream);
317 *OutStream << " seconds (";
318 printAlignedFP(Total.getWallTime(), 4, 5, *OutStream);
319 *OutStream << " wall clock)\n\n";
322 *OutStream << " ---User Time---";
323 if (Total.SystemTime)
324 *OutStream << " --System Time--";
325 if (Total.getProcessTime())
326 *OutStream << " --User+System--";
327 *OutStream << " ---Wall Time---";
328 if (Total.getMemUsed())
329 *OutStream << " ---Mem---";
330 if (Total.getPeakMem())
331 *OutStream << " -PeakMem-";
332 *OutStream << " --- Name ---\n";
334 // Loop through all of the timing data, printing it out...
335 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
336 TimersToPrint[i].print(Total, *OutStream);
338 Total.print(Total, *OutStream);
339 *OutStream << std::endl; // Flush output
343 TimersToPrint.clear();
345 if (OutStream != &std::cerr && OutStream != &std::cout)
346 delete OutStream; // Close the file...
349 // Delete default timer group!
350 if (NumTimers == 0 && this == DefaultTimerGroup) {
351 delete DefaultTimerGroup;
352 DefaultTimerGroup = 0;
356 } // End llvm namespace