1 //===-- Timer.cpp - Interval Timing Support -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Interval Timing implementation.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/Debug.h"
15 #include "llvm/Support/Timer.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/ManagedStatic.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/System/Process.h"
26 // GetLibSupportInfoOutputFile - Return a file stream to print our output on.
27 namespace llvm { extern raw_ostream *GetLibSupportInfoOutputFile(); }
29 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
30 // of constructor/destructor ordering being unspecified by C++. Basically the
31 // problem is that a Statistic object gets destroyed, which ends up calling
32 // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
33 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
34 // would get destroyed before the Statistic, causing havoc to ensue. We "fix"
35 // this by creating the string the first time it is needed and never destroying
37 static ManagedStatic<std::string> LibSupportInfoOutputFilename;
38 static std::string &getLibSupportInfoOutputFilename() {
39 return *LibSupportInfoOutputFilename;
42 static ManagedStatic<sys::SmartMutex<true> > TimerLock;
46 TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
47 "tracking (this may be slow)"),
50 static cl::opt<std::string, true>
51 InfoOutputFilename("info-output-file", cl::value_desc("filename"),
52 cl::desc("File to append -stats and -timer output to"),
53 cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
56 static TimerGroup *DefaultTimerGroup = 0;
57 static TimerGroup *getDefaultTimerGroup() {
58 TimerGroup *tmp = DefaultTimerGroup;
62 llvm_acquire_global_lock();
63 tmp = DefaultTimerGroup;
65 tmp = new TimerGroup("Miscellaneous Ungrouped Timers");
67 DefaultTimerGroup = tmp;
69 llvm_release_global_lock();
74 //===----------------------------------------------------------------------===//
75 // Timer Implementation
76 //===----------------------------------------------------------------------===//
78 Timer::Timer(const std::string &N)
79 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
80 Started(false), TG(getDefaultTimerGroup()) {
84 Timer::Timer(const std::string &N, TimerGroup &tg)
85 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
86 Started(false), TG(&tg) {
90 Timer::Timer(const Timer &T) {
92 if (TG) TG->addTimer();
96 // Copy ctor, initialize with no TG member.
97 Timer::Timer(bool, const Timer &T) {
98 TG = T.TG; // Avoid assertion in operator=
99 operator=(T); // Copy contents
108 TG->addTimerToPrint(*this);
113 static inline size_t getMemUsage() {
115 return sys::Process::GetMallocUsage();
120 double Elapsed, UserTime, SystemTime;
124 static TimeRecord getTimeRecord(bool Start) {
127 sys::TimeValue now(0,0);
128 sys::TimeValue user(0,0);
129 sys::TimeValue sys(0,0);
133 MemUsed = getMemUsage();
134 sys::Process::GetTimeUsage(now, user, sys);
136 sys::Process::GetTimeUsage(now, user, sys);
137 MemUsed = getMemUsage();
140 Result.Elapsed = now.seconds() + now.microseconds() / 1000000.0;
141 Result.UserTime = user.seconds() + user.microseconds() / 1000000.0;
142 Result.SystemTime = sys.seconds() + sys.microseconds() / 1000000.0;
143 Result.MemUsed = MemUsed;
147 static ManagedStatic<std::vector<Timer*> > ActiveTimers;
149 void Timer::startTimer() {
151 ActiveTimers->push_back(this);
152 TimeRecord TR = getTimeRecord(true);
153 Elapsed -= TR.Elapsed;
154 UserTime -= TR.UserTime;
155 SystemTime -= TR.SystemTime;
156 MemUsed -= TR.MemUsed;
157 PeakMemBase = TR.MemUsed;
160 void Timer::stopTimer() {
161 TimeRecord TR = getTimeRecord(false);
162 Elapsed += TR.Elapsed;
163 UserTime += TR.UserTime;
164 SystemTime += TR.SystemTime;
165 MemUsed += TR.MemUsed;
167 if (ActiveTimers->back() == this) {
168 ActiveTimers->pop_back();
170 std::vector<Timer*>::iterator I =
171 std::find(ActiveTimers->begin(), ActiveTimers->end(), this);
172 assert(I != ActiveTimers->end() && "stop but no startTimer?");
173 ActiveTimers->erase(I);
177 void Timer::sum(const Timer &T) {
178 Elapsed += T.Elapsed;
179 UserTime += T.UserTime;
180 SystemTime += T.SystemTime;
181 MemUsed += T.MemUsed;
182 PeakMem += T.PeakMem;
185 const Timer &Timer::operator=(const Timer &T) {
187 UserTime = T.UserTime;
188 SystemTime = T.SystemTime;
191 PeakMemBase = T.PeakMemBase;
194 assert(TG == T.TG && "Can only assign timers in the same TimerGroup!");
199 /// addPeakMemoryMeasurement - This method should be called whenever memory
200 /// usage needs to be checked. It adds a peak memory measurement to the
201 /// currently active timers, which will be printed when the timer group prints
203 void Timer::addPeakMemoryMeasurement() {
204 size_t MemUsed = getMemUsage();
205 for (std::vector<Timer*>::iterator I = ActiveTimers->begin(),
206 E = ActiveTimers->end(); I != E; ++I)
207 (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase);
211 static void printVal(double Val, double Total, raw_ostream &OS) {
212 if (Total < 1e-7) // Avoid dividing by zero.
215 OS << " " << format("%7.4f", Val) << " (";
216 OS << format("%5.1f", Val*100/Total) << "%)";
220 void Timer::print(const Timer &Total, raw_ostream &OS) {
222 printVal(UserTime, Total.UserTime, OS);
223 if (Total.SystemTime)
224 printVal(SystemTime, Total.SystemTime, OS);
225 if (Total.getProcessTime())
226 printVal(getProcessTime(), Total.getProcessTime(), OS);
227 printVal(Elapsed, Total.Elapsed, OS);
232 OS << format("%9lld", (long long)MemUsed) << " ";
236 OS << format("%9lld", (long long)PeakMem) << " ";
242 Started = false; // Once printed, don't print again
246 //===----------------------------------------------------------------------===//
247 // NamedRegionTimer Implementation
248 //===----------------------------------------------------------------------===//
250 typedef std::map<std::string, Timer> Name2Timer;
251 typedef std::map<std::string, std::pair<TimerGroup, Name2Timer> > Name2Pair;
253 static ManagedStatic<Name2Timer> NamedTimers;
254 static ManagedStatic<Name2Pair> NamedGroupedTimers;
256 static Timer &getNamedRegionTimer(const std::string &Name) {
257 sys::SmartScopedLock<true> L(*TimerLock);
258 Name2Timer::iterator I = NamedTimers->find(Name);
259 if (I != NamedTimers->end())
262 return NamedTimers->insert(I, std::make_pair(Name, Timer(Name)))->second;
265 static Timer &getNamedRegionTimer(const std::string &Name,
266 const std::string &GroupName) {
267 sys::SmartScopedLock<true> L(*TimerLock);
269 Name2Pair::iterator I = NamedGroupedTimers->find(GroupName);
270 if (I == NamedGroupedTimers->end()) {
271 TimerGroup TG(GroupName);
272 std::pair<TimerGroup, Name2Timer> Pair(TG, Name2Timer());
273 I = NamedGroupedTimers->insert(I, std::make_pair(GroupName, Pair));
276 Name2Timer::iterator J = I->second.second.find(Name);
277 if (J == I->second.second.end())
278 J = I->second.second.insert(J,
286 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
287 : TimeRegion(getNamedRegionTimer(Name)) {}
289 NamedRegionTimer::NamedRegionTimer(const std::string &Name,
290 const std::string &GroupName)
291 : TimeRegion(getNamedRegionTimer(Name, GroupName)) {}
293 //===----------------------------------------------------------------------===//
294 // TimerGroup Implementation
295 //===----------------------------------------------------------------------===//
297 // GetLibSupportInfoOutputFile - Return a file stream to print our output on.
298 raw_ostream *llvm::GetLibSupportInfoOutputFile() {
299 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
300 if (LibSupportInfoOutputFilename.empty())
302 if (LibSupportInfoOutputFilename == "-")
306 raw_ostream *Result = new raw_fd_ostream(LibSupportInfoOutputFilename.c_str(),
307 Error, raw_fd_ostream::F_Append);
311 errs() << "Error opening info-output-file '"
312 << LibSupportInfoOutputFilename << " for appending!\n";
318 void TimerGroup::removeTimer() {
319 sys::SmartScopedLock<true> L(*TimerLock);
320 if (--NumTimers != 0 || TimersToPrint.empty())
321 return; // Don't print timing report.
323 // Sort the timers in descending order by amount of time taken.
324 std::sort(TimersToPrint.begin(), TimersToPrint.end(),
325 std::greater<Timer>());
327 // Figure out how many spaces to indent TimerGroup name.
328 unsigned Padding = (80-Name.length())/2;
329 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
331 raw_ostream *OutStream = GetLibSupportInfoOutputFile();
334 { // Scope to contain Total timer: don't allow total timer to drop us to
336 Timer Total("TOTAL");
338 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
339 Total.sum(TimersToPrint[i]);
341 // Print out timing header.
342 *OutStream << "===" << std::string(73, '-') << "===\n"
343 << std::string(Padding, ' ') << Name << "\n"
344 << "===" << std::string(73, '-')
347 // If this is not an collection of ungrouped times, print the total time.
348 // Ungrouped timers don't really make sense to add up. We still print the
349 // TOTAL line to make the percentages make sense.
350 if (this != DefaultTimerGroup) {
351 *OutStream << " Total Execution Time: ";
353 *OutStream << format("%5.4f", Total.getProcessTime()) << " seconds (";
354 *OutStream << format("%5.4f", Total.getWallTime()) << " wall clock)\n";
359 *OutStream << " ---User Time---";
360 if (Total.SystemTime)
361 *OutStream << " --System Time--";
362 if (Total.getProcessTime())
363 *OutStream << " --User+System--";
364 *OutStream << " ---Wall Time---";
365 if (Total.getMemUsed())
366 *OutStream << " ---Mem---";
367 if (Total.getPeakMem())
368 *OutStream << " -PeakMem-";
369 *OutStream << " --- Name ---\n";
371 // Loop through all of the timing data, printing it out.
372 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
373 TimersToPrint[i].print(Total, *OutStream);
375 Total.print(Total, *OutStream);
381 TimersToPrint.clear();
383 if (OutStream != &errs() && OutStream != &outs())
384 delete OutStream; // Close the file.
387 void TimerGroup::addTimer() {
388 sys::SmartScopedLock<true> L(*TimerLock);
392 void TimerGroup::addTimerToPrint(const Timer &T) {
393 sys::SmartScopedLock<true> L(*TimerLock);
394 TimersToPrint.push_back(Timer(true, T));