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 "llvm/Support/Timer.h"
15 #include "llvm/Support/CommandLine.h"
16 #include "llvm/System/Process.h"
25 // GetLibSupportInfoOutputFile - Return a file stream to print our output on.
26 namespace llvm { extern std::ostream *GetLibSupportInfoOutputFile(); }
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;
43 TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
44 "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);
97 double Elapsed, UserTime, SystemTime;
101 static TimeRecord getTimeRecord(bool Start) {
104 sys::TimeValue now(0,0);
105 sys::TimeValue user(0,0);
106 sys::TimeValue sys(0,0);
110 sys::Process::GetTimeUsage(now,user,sys);
111 MemUsed = sys::Process::GetMallocUsage();
113 MemUsed = sys::Process::GetMallocUsage();
114 sys::Process::GetTimeUsage(now,user,sys);
117 Result.Elapsed = now.seconds() + now.microseconds() / 1000000.0;
118 Result.UserTime = user.seconds() + user.microseconds() / 1000000.0;
119 Result.SystemTime = sys.seconds() + sys.microseconds() / 1000000.0;
120 Result.MemUsed = MemUsed;
125 static std::vector<Timer*> ActiveTimers;
127 void Timer::startTimer() {
129 TimeRecord TR = getTimeRecord(true);
130 Elapsed -= TR.Elapsed;
131 UserTime -= TR.UserTime;
132 SystemTime -= TR.SystemTime;
133 MemUsed -= TR.MemUsed;
134 PeakMemBase = TR.MemUsed;
135 ActiveTimers.push_back(this);
138 void Timer::stopTimer() {
139 TimeRecord TR = getTimeRecord(false);
140 Elapsed += TR.Elapsed;
141 UserTime += TR.UserTime;
142 SystemTime += TR.SystemTime;
143 MemUsed += TR.MemUsed;
145 if (ActiveTimers.back() == this) {
146 ActiveTimers.pop_back();
148 std::vector<Timer*>::iterator I =
149 std::find(ActiveTimers.begin(), ActiveTimers.end(), this);
150 assert(I != ActiveTimers.end() && "stop but no startTimer?");
151 ActiveTimers.erase(I);
155 void Timer::sum(const Timer &T) {
156 Elapsed += T.Elapsed;
157 UserTime += T.UserTime;
158 SystemTime += T.SystemTime;
159 MemUsed += T.MemUsed;
160 PeakMem += T.PeakMem;
163 /// addPeakMemoryMeasurement - This method should be called whenever memory
164 /// usage needs to be checked. It adds a peak memory measurement to the
165 /// currently active timers, which will be printed when the timer group prints
167 void Timer::addPeakMemoryMeasurement() {
168 long MemUsed = sys::Process::GetMallocUsage();
170 for (std::vector<Timer*>::iterator I = ActiveTimers.begin(),
171 E = ActiveTimers.end(); I != E; ++I)
172 (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase);
175 //===----------------------------------------------------------------------===//
176 // NamedRegionTimer Implementation
177 //===----------------------------------------------------------------------===//
179 static Timer &getNamedRegionTimer(const std::string &Name) {
180 static std::map<std::string, Timer> NamedTimers;
182 std::map<std::string, Timer>::iterator I = NamedTimers.lower_bound(Name);
183 if (I != NamedTimers.end() && I->first == Name)
186 return NamedTimers.insert(I, std::make_pair(Name, Timer(Name)))->second;
189 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
190 : TimeRegion(getNamedRegionTimer(Name)) {}
193 //===----------------------------------------------------------------------===//
194 // TimerGroup Implementation
195 //===----------------------------------------------------------------------===//
197 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
198 // TotalWidth size, and B is the AfterDec size.
200 static void printAlignedFP(double Val, unsigned AfterDec, unsigned TotalWidth,
202 assert(TotalWidth >= AfterDec+1 && "Bad FP Format!");
203 OS.width(TotalWidth-AfterDec-1);
204 char OldFill = OS.fill();
206 OS << (int)Val; // Integer part;
210 unsigned ResultFieldSize = 1;
211 while (AfterDec--) ResultFieldSize *= 10;
212 OS << (int)(Val*ResultFieldSize) % ResultFieldSize;
216 static void printVal(double Val, double Total, std::ostream &OS) {
217 if (Total < 1e-7) // Avoid dividing by zero...
221 printAlignedFP(Val, 4, 7, OS);
223 printAlignedFP(Val*100/Total, 1, 5, OS);
228 void Timer::print(const Timer &Total, std::ostream &OS) {
230 printVal(UserTime, Total.UserTime, OS);
231 if (Total.SystemTime)
232 printVal(SystemTime, Total.SystemTime, OS);
233 if (Total.getProcessTime())
234 printVal(getProcessTime(), Total.getProcessTime(), OS);
235 printVal(Elapsed, Total.Elapsed, OS);
241 OS << MemUsed << " ";
246 OS << PeakMem << " ";
252 Started = false; // Once printed, don't print again
255 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
257 llvm::GetLibSupportInfoOutputFile() {
258 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
259 if (LibSupportInfoOutputFilename.empty())
261 if (LibSupportInfoOutputFilename == "-")
264 std::ostream *Result = new std::ofstream(LibSupportInfoOutputFilename.c_str(),
266 if (!Result->good()) {
267 std::cerr << "Error opening info-output-file '"
268 << LibSupportInfoOutputFilename << " for appending!\n";
276 void TimerGroup::removeTimer() {
277 if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report...
278 // Sort the timers in descending order by amount of time taken...
279 std::sort(TimersToPrint.begin(), TimersToPrint.end(),
280 std::greater<Timer>());
282 // Figure out how many spaces to indent TimerGroup name...
283 unsigned Padding = (80-Name.length())/2;
284 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
286 std::ostream *OutStream = GetLibSupportInfoOutputFile();
289 { // Scope to contain Total timer... don't allow total timer to drop us to
291 Timer Total("TOTAL");
293 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
294 Total.sum(TimersToPrint[i]);
296 // Print out timing header...
297 *OutStream << "===" << std::string(73, '-') << "===\n"
298 << std::string(Padding, ' ') << Name << "\n"
299 << "===" << std::string(73, '-')
300 << "===\n Total Execution Time: ";
302 printAlignedFP(Total.getProcessTime(), 4, 5, *OutStream);
303 *OutStream << " seconds (";
304 printAlignedFP(Total.getWallTime(), 4, 5, *OutStream);
305 *OutStream << " wall clock)\n\n";
308 *OutStream << " ---User Time---";
309 if (Total.SystemTime)
310 *OutStream << " --System Time--";
311 if (Total.getProcessTime())
312 *OutStream << " --User+System--";
313 *OutStream << " ---Wall Time---";
314 if (Total.getMemUsed())
315 *OutStream << " ---Mem---";
316 if (Total.getPeakMem())
317 *OutStream << " -PeakMem-";
318 *OutStream << " --- Name ---\n";
320 // Loop through all of the timing data, printing it out...
321 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
322 TimersToPrint[i].print(Total, *OutStream);
324 Total.print(Total, *OutStream);
325 *OutStream << std::endl; // Flush output
329 TimersToPrint.clear();
331 if (OutStream != &std::cerr && OutStream != &std::cout)
332 delete OutStream; // Close the file...
335 // Delete default timer group!
336 if (NumTimers == 0 && this == DefaultTimerGroup) {
337 delete DefaultTimerGroup;
338 DefaultTimerGroup = 0;