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"
27 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
28 namespace llvm { extern std::ostream *GetLibSupportInfoOutputFile(); }
30 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
31 // of constructor/destructor ordering being unspecified by C++. Basically the
32 // problem is that a Statistic<> object gets destroyed, which ends up calling
33 // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
34 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
35 // would get destroyed before the Statistic, causing havoc to ensue. We "fix"
36 // this by creating the string the first time it is needed and never destroying
38 static std::string &getLibSupportInfoOutputFilename() {
39 static std::string *LibSupportInfoOutputFilename = new std::string();
40 return *LibSupportInfoOutputFilename;
46 TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
47 "tracking (this may be slow)"),
51 cl::opt<std::string, true>
52 InfoOutputFilename("info-output-file", cl::value_desc("filename"),
53 cl::desc("File to append -stats and -timer output to"),
54 cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
57 static TimerGroup *DefaultTimerGroup = 0;
58 static TimerGroup *getDefaultTimerGroup() {
59 if (DefaultTimerGroup) return DefaultTimerGroup;
60 return DefaultTimerGroup = new TimerGroup("Miscellaneous Ungrouped Timers");
63 Timer::Timer(const std::string &N)
64 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
65 Started(false), TG(getDefaultTimerGroup()) {
69 Timer::Timer(const std::string &N, TimerGroup &tg)
70 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
71 Started(false), TG(&tg) {
75 Timer::Timer(const Timer &T) {
77 if (TG) TG->addTimer();
82 // Copy ctor, initialize with no TG member.
83 Timer::Timer(bool, const Timer &T) {
84 TG = T.TG; // Avoid assertion in operator=
85 operator=(T); // Copy contents
94 TG->addTimerToPrint(*this);
100 static long getMemUsage() {
103 struct mallinfo MI = mallinfo();
104 return MI.uordblks/*+MI.hblkhd*/;
111 double Elapsed, UserTime, SystemTime;
115 static TimeRecord getTimeRecord(bool Start) {
120 MemUsed = getMemUsage();
121 if (getrusage(RUSAGE_SELF, &RU))
122 perror("getrusage call failed: -time-passes info incorrect!");
127 if (getrusage(RUSAGE_SELF, &RU))
128 perror("getrusage call failed: -time-passes info incorrect!");
129 MemUsed = getMemUsage();
133 Result.Elapsed = T.tv_sec + T.tv_usec/1000000.0;
134 Result.UserTime = RU.ru_utime.tv_sec + RU.ru_utime.tv_usec/1000000.0;
135 Result.SystemTime = RU.ru_stime.tv_sec + RU.ru_stime.tv_usec/1000000.0;
136 Result.MemUsed = MemUsed;
141 static std::vector<Timer*> ActiveTimers;
143 void Timer::startTimer() {
145 TimeRecord TR = getTimeRecord(true);
146 Elapsed -= TR.Elapsed;
147 UserTime -= TR.UserTime;
148 SystemTime -= TR.SystemTime;
149 MemUsed -= TR.MemUsed;
150 PeakMemBase = TR.MemUsed;
151 ActiveTimers.push_back(this);
154 void Timer::stopTimer() {
155 TimeRecord TR = getTimeRecord(false);
156 Elapsed += TR.Elapsed;
157 UserTime += TR.UserTime;
158 SystemTime += TR.SystemTime;
159 MemUsed += TR.MemUsed;
161 if (ActiveTimers.back() == this) {
162 ActiveTimers.pop_back();
164 std::vector<Timer*>::iterator I =
165 std::find(ActiveTimers.begin(), ActiveTimers.end(), this);
166 assert(I != ActiveTimers.end() && "stop but no startTimer?");
167 ActiveTimers.erase(I);
171 void Timer::sum(const Timer &T) {
172 Elapsed += T.Elapsed;
173 UserTime += T.UserTime;
174 SystemTime += T.SystemTime;
175 MemUsed += T.MemUsed;
176 PeakMem += T.PeakMem;
179 /// addPeakMemoryMeasurement - This method should be called whenever memory
180 /// usage needs to be checked. It adds a peak memory measurement to the
181 /// currently active timers, which will be printed when the timer group prints
183 void Timer::addPeakMemoryMeasurement() {
184 long MemUsed = getMemUsage();
186 for (std::vector<Timer*>::iterator I = ActiveTimers.begin(),
187 E = ActiveTimers.end(); I != E; ++I)
188 (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase);
191 //===----------------------------------------------------------------------===//
192 // NamedRegionTimer Implementation
193 //===----------------------------------------------------------------------===//
195 static Timer &getNamedRegionTimer(const std::string &Name) {
196 static std::map<std::string, Timer> NamedTimers;
198 std::map<std::string, Timer>::iterator I = NamedTimers.lower_bound(Name);
199 if (I != NamedTimers.end() && I->first == Name)
202 return NamedTimers.insert(I, std::make_pair(Name, Timer(Name)))->second;
205 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
206 : TimeRegion(getNamedRegionTimer(Name)) {}
209 //===----------------------------------------------------------------------===//
210 // TimerGroup Implementation
211 //===----------------------------------------------------------------------===//
213 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
214 // TotalWidth size, and B is the AfterDec size.
216 static void printAlignedFP(double Val, unsigned AfterDec, unsigned TotalWidth,
218 assert(TotalWidth >= AfterDec+1 && "Bad FP Format!");
219 OS.width(TotalWidth-AfterDec-1);
220 char OldFill = OS.fill();
222 OS << (int)Val; // Integer part;
226 unsigned ResultFieldSize = 1;
227 while (AfterDec--) ResultFieldSize *= 10;
228 OS << (int)(Val*ResultFieldSize) % ResultFieldSize;
232 static void printVal(double Val, double Total, std::ostream &OS) {
233 if (Total < 1e-7) // Avoid dividing by zero...
237 printAlignedFP(Val, 4, 7, OS);
239 printAlignedFP(Val*100/Total, 1, 5, OS);
244 void Timer::print(const Timer &Total, std::ostream &OS) {
246 printVal(UserTime, Total.UserTime, OS);
247 if (Total.SystemTime)
248 printVal(SystemTime, Total.SystemTime, OS);
249 if (Total.getProcessTime())
250 printVal(getProcessTime(), Total.getProcessTime(), OS);
251 printVal(Elapsed, Total.Elapsed, OS);
257 OS << MemUsed << " ";
262 OS << PeakMem << " ";
268 Started = false; // Once printed, don't print again
271 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
273 llvm::GetLibSupportInfoOutputFile() {
274 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
275 if (LibSupportInfoOutputFilename.empty())
277 if (LibSupportInfoOutputFilename == "-")
280 std::ostream *Result = new std::ofstream(LibSupportInfoOutputFilename.c_str(),
282 if (!Result->good()) {
283 std::cerr << "Error opening info-output-file '"
284 << LibSupportInfoOutputFilename << " for appending!\n";
292 void TimerGroup::removeTimer() {
293 if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report...
294 // Sort the timers in descending order by amount of time taken...
295 std::sort(TimersToPrint.begin(), TimersToPrint.end(),
296 std::greater<Timer>());
298 // Figure out how many spaces to indent TimerGroup name...
299 unsigned Padding = (80-Name.length())/2;
300 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
302 std::ostream *OutStream = GetLibSupportInfoOutputFile();
305 { // Scope to contain Total timer... don't allow total timer to drop us to
307 Timer Total("TOTAL");
309 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
310 Total.sum(TimersToPrint[i]);
312 // Print out timing header...
313 *OutStream << "===" << std::string(73, '-') << "===\n"
314 << std::string(Padding, ' ') << Name << "\n"
315 << "===" << std::string(73, '-')
316 << "===\n Total Execution Time: ";
318 printAlignedFP(Total.getProcessTime(), 4, 5, *OutStream);
319 *OutStream << " seconds (";
320 printAlignedFP(Total.getWallTime(), 4, 5, *OutStream);
321 *OutStream << " wall clock)\n\n";
324 *OutStream << " ---User Time---";
325 if (Total.SystemTime)
326 *OutStream << " --System Time--";
327 if (Total.getProcessTime())
328 *OutStream << " --User+System--";
329 *OutStream << " ---Wall Time---";
330 if (Total.getMemUsed())
331 *OutStream << " ---Mem---";
332 if (Total.getPeakMem())
333 *OutStream << " -PeakMem-";
334 *OutStream << " --- Name ---\n";
336 // Loop through all of the timing data, printing it out...
337 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
338 TimersToPrint[i].print(Total, *OutStream);
340 Total.print(Total, *OutStream);
341 *OutStream << std::endl; // Flush output
345 TimersToPrint.clear();
347 if (OutStream != &std::cerr && OutStream != &std::cout)
348 delete OutStream; // Close the file...
351 // Delete default timer group!
352 if (NumTimers == 0 && this == DefaultTimerGroup) {
353 delete DefaultTimerGroup;
354 DefaultTimerGroup = 0;