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"
21 #include "Config/sys/resource.h"
22 #include "Config/sys/time.h"
23 #include "Config/unistd.h"
24 #include "Config/malloc.h"
25 #include "Config/windows.h"
28 // GetLibSupportInfoOutputFile - Return a file stream to print our output on.
29 namespace llvm { extern std::ostream *GetLibSupportInfoOutputFile(); }
31 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
32 // of constructor/destructor ordering being unspecified by C++. Basically the
33 // problem is that a Statistic<> object gets destroyed, which ends up calling
34 // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
35 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
36 // would get destroyed before the Statistic, causing havoc to ensue. We "fix"
37 // this by creating the string the first time it is needed and never destroying
39 static std::string &getLibSupportInfoOutputFilename() {
40 static std::string *LibSupportInfoOutputFilename = new std::string();
41 return *LibSupportInfoOutputFilename;
47 TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
48 "tracking (this may be slow)"),
52 cl::opt<std::string, true>
53 InfoOutputFilename("info-output-file", cl::value_desc("filename"),
54 cl::desc("File to append -stats and -timer output to"),
55 cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
58 static TimerGroup *DefaultTimerGroup = 0;
59 static TimerGroup *getDefaultTimerGroup() {
60 if (DefaultTimerGroup) return DefaultTimerGroup;
61 return DefaultTimerGroup = new TimerGroup("Miscellaneous Ungrouped Timers");
64 Timer::Timer(const std::string &N)
65 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
66 Started(false), TG(getDefaultTimerGroup()) {
70 Timer::Timer(const std::string &N, TimerGroup &tg)
71 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
72 Started(false), TG(&tg) {
76 Timer::Timer(const Timer &T) {
78 if (TG) TG->addTimer();
83 // Copy ctor, initialize with no TG member.
84 Timer::Timer(bool, const Timer &T) {
85 TG = T.TG; // Avoid assertion in operator=
86 operator=(T); // Copy contents
95 TG->addTimerToPrint(*this);
101 static long getMemUsage() {
104 struct mallinfo MI = mallinfo();
105 return MI.uordblks/*+MI.hblkhd*/;
112 double Elapsed, UserTime, SystemTime;
116 static TimeRecord getTimeRecord(bool Start) {
117 #if defined(HAVE_WINDOWS_H)
118 unsigned __int64 ProcCreate, ProcExit, KernelTime, UserTime, CurTime;
120 GetProcessTimes(GetCurrentProcess(), (FILETIME*)&ProcCreate,
121 (FILETIME*)&ProcExit, (FILETIME*)&KernelTime,
122 (FILETIME*)&UserTime);
123 GetSystemTimeAsFileTime((FILETIME*)&CurTime);
125 // FILETIME's are # of 100 nanosecond ticks.
126 double ScaleFactor = 1.0/(10*1000*1000);
129 Result.Elapsed = (CurTime-ProcCreate)*ScaleFactor; // Wall time
130 Result.UserTime = UserTime*ScaleFactor;
131 Result.SystemTime = KernelTime*ScaleFactor;
133 #elif defined(HAVE_GETRUSAGE)
138 MemUsed = getMemUsage();
139 if (getrusage(RUSAGE_SELF, &RU))
140 perror("getrusage call failed: -time-passes info incorrect!");
145 if (getrusage(RUSAGE_SELF, &RU))
146 perror("getrusage call failed: -time-passes info incorrect!");
147 MemUsed = getMemUsage();
151 Result.Elapsed = T.tv_sec + T.tv_usec/1000000.0;
152 Result.UserTime = RU.ru_utime.tv_sec + RU.ru_utime.tv_usec/1000000.0;
153 Result.SystemTime = RU.ru_stime.tv_sec + RU.ru_stime.tv_usec/1000000.0;
154 Result.MemUsed = MemUsed;
157 // Can't get resource usage.
162 static std::vector<Timer*> ActiveTimers;
164 void Timer::startTimer() {
166 TimeRecord TR = getTimeRecord(true);
167 Elapsed -= TR.Elapsed;
168 UserTime -= TR.UserTime;
169 SystemTime -= TR.SystemTime;
170 MemUsed -= TR.MemUsed;
171 PeakMemBase = TR.MemUsed;
172 ActiveTimers.push_back(this);
175 void Timer::stopTimer() {
176 TimeRecord TR = getTimeRecord(false);
177 Elapsed += TR.Elapsed;
178 UserTime += TR.UserTime;
179 SystemTime += TR.SystemTime;
180 MemUsed += TR.MemUsed;
182 if (ActiveTimers.back() == this) {
183 ActiveTimers.pop_back();
185 std::vector<Timer*>::iterator I =
186 std::find(ActiveTimers.begin(), ActiveTimers.end(), this);
187 assert(I != ActiveTimers.end() && "stop but no startTimer?");
188 ActiveTimers.erase(I);
192 void Timer::sum(const Timer &T) {
193 Elapsed += T.Elapsed;
194 UserTime += T.UserTime;
195 SystemTime += T.SystemTime;
196 MemUsed += T.MemUsed;
197 PeakMem += T.PeakMem;
200 /// addPeakMemoryMeasurement - This method should be called whenever memory
201 /// usage needs to be checked. It adds a peak memory measurement to the
202 /// currently active timers, which will be printed when the timer group prints
204 void Timer::addPeakMemoryMeasurement() {
205 long MemUsed = getMemUsage();
207 for (std::vector<Timer*>::iterator I = ActiveTimers.begin(),
208 E = ActiveTimers.end(); I != E; ++I)
209 (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase);
212 //===----------------------------------------------------------------------===//
213 // NamedRegionTimer Implementation
214 //===----------------------------------------------------------------------===//
216 static Timer &getNamedRegionTimer(const std::string &Name) {
217 static std::map<std::string, Timer> NamedTimers;
219 std::map<std::string, Timer>::iterator I = NamedTimers.lower_bound(Name);
220 if (I != NamedTimers.end() && I->first == Name)
223 return NamedTimers.insert(I, std::make_pair(Name, Timer(Name)))->second;
226 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
227 : TimeRegion(getNamedRegionTimer(Name)) {}
230 //===----------------------------------------------------------------------===//
231 // TimerGroup Implementation
232 //===----------------------------------------------------------------------===//
234 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
235 // TotalWidth size, and B is the AfterDec size.
237 static void printAlignedFP(double Val, unsigned AfterDec, unsigned TotalWidth,
239 assert(TotalWidth >= AfterDec+1 && "Bad FP Format!");
240 OS.width(TotalWidth-AfterDec-1);
241 char OldFill = OS.fill();
243 OS << (int)Val; // Integer part;
247 unsigned ResultFieldSize = 1;
248 while (AfterDec--) ResultFieldSize *= 10;
249 OS << (int)(Val*ResultFieldSize) % ResultFieldSize;
253 static void printVal(double Val, double Total, std::ostream &OS) {
254 if (Total < 1e-7) // Avoid dividing by zero...
258 printAlignedFP(Val, 4, 7, OS);
260 printAlignedFP(Val*100/Total, 1, 5, OS);
265 void Timer::print(const Timer &Total, std::ostream &OS) {
267 printVal(UserTime, Total.UserTime, OS);
268 if (Total.SystemTime)
269 printVal(SystemTime, Total.SystemTime, OS);
270 if (Total.getProcessTime())
271 printVal(getProcessTime(), Total.getProcessTime(), OS);
272 printVal(Elapsed, Total.Elapsed, OS);
278 OS << MemUsed << " ";
283 OS << PeakMem << " ";
289 Started = false; // Once printed, don't print again
292 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
294 llvm::GetLibSupportInfoOutputFile() {
295 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
296 if (LibSupportInfoOutputFilename.empty())
298 if (LibSupportInfoOutputFilename == "-")
301 std::ostream *Result = new std::ofstream(LibSupportInfoOutputFilename.c_str(),
303 if (!Result->good()) {
304 std::cerr << "Error opening info-output-file '"
305 << LibSupportInfoOutputFilename << " for appending!\n";
313 void TimerGroup::removeTimer() {
314 if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report...
315 // Sort the timers in descending order by amount of time taken...
316 std::sort(TimersToPrint.begin(), TimersToPrint.end(),
317 std::greater<Timer>());
319 // Figure out how many spaces to indent TimerGroup name...
320 unsigned Padding = (80-Name.length())/2;
321 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
323 std::ostream *OutStream = GetLibSupportInfoOutputFile();
326 { // Scope to contain Total timer... don't allow total timer to drop us to
328 Timer Total("TOTAL");
330 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
331 Total.sum(TimersToPrint[i]);
333 // Print out timing header...
334 *OutStream << "===" << std::string(73, '-') << "===\n"
335 << std::string(Padding, ' ') << Name << "\n"
336 << "===" << std::string(73, '-')
337 << "===\n Total Execution Time: ";
339 printAlignedFP(Total.getProcessTime(), 4, 5, *OutStream);
340 *OutStream << " seconds (";
341 printAlignedFP(Total.getWallTime(), 4, 5, *OutStream);
342 *OutStream << " wall clock)\n\n";
345 *OutStream << " ---User Time---";
346 if (Total.SystemTime)
347 *OutStream << " --System Time--";
348 if (Total.getProcessTime())
349 *OutStream << " --User+System--";
350 *OutStream << " ---Wall Time---";
351 if (Total.getMemUsed())
352 *OutStream << " ---Mem---";
353 if (Total.getPeakMem())
354 *OutStream << " -PeakMem-";
355 *OutStream << " --- Name ---\n";
357 // Loop through all of the timing data, printing it out...
358 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
359 TimersToPrint[i].print(Total, *OutStream);
361 Total.print(Total, *OutStream);
362 *OutStream << std::endl; // Flush output
366 TimersToPrint.clear();
368 if (OutStream != &std::cerr && OutStream != &std::cout)
369 delete OutStream; // Close the file...
372 // Delete default timer group!
373 if (NumTimers == 0 && this == DefaultTimerGroup) {
374 delete DefaultTimerGroup;
375 DefaultTimerGroup = 0;