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/Timer.h"
15 #include "llvm/Support/CommandLine.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/ManagedStatic.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/System/Mutex.h"
21 #include "llvm/System/Process.h"
22 #include "llvm/ADT/OwningPtr.h"
23 #include "llvm/ADT/StringMap.h"
26 // CreateInfoOutputFile - Return a file stream to print our output on.
27 namespace llvm { extern raw_ostream *CreateInfoOutputFile(); }
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 // CreateInfoOutputFile - Return a file stream to print our output on.
57 raw_ostream *llvm::CreateInfoOutputFile() {
58 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
59 if (LibSupportInfoOutputFilename.empty())
60 return new raw_fd_ostream(2, false); // stderr.
61 if (LibSupportInfoOutputFilename == "-")
62 return new raw_fd_ostream(1, false); // stdout.
65 raw_ostream *Result = new raw_fd_ostream(LibSupportInfoOutputFilename.c_str(),
66 Error, raw_fd_ostream::F_Append);
70 errs() << "Error opening info-output-file '"
71 << LibSupportInfoOutputFilename << " for appending!\n";
73 return new raw_fd_ostream(2, false); // stderr.
77 static TimerGroup *DefaultTimerGroup = 0;
78 static TimerGroup *getDefaultTimerGroup() {
79 TimerGroup *tmp = DefaultTimerGroup;
83 llvm_acquire_global_lock();
84 tmp = DefaultTimerGroup;
86 tmp = new TimerGroup("Miscellaneous Ungrouped Timers");
88 DefaultTimerGroup = tmp;
90 llvm_release_global_lock();
95 //===----------------------------------------------------------------------===//
96 // Timer Implementation
97 //===----------------------------------------------------------------------===//
99 void Timer::init(const std::string &N) {
100 assert(TG == 0 && "Timer already initialized");
103 TG = getDefaultTimerGroup();
107 void Timer::init(const std::string &N, TimerGroup &tg) {
108 assert(TG == 0 && "Timer already initialized");
116 if (!TG) return; // Never initialized, or already cleared.
117 TG->removeTimer(*this);
120 static inline size_t getMemUsage() {
121 if (!TrackSpace) return 0;
122 return sys::Process::GetMallocUsage();
125 TimeRecord TimeRecord::getCurrentTime(bool Start) {
127 sys::TimeValue now(0,0), user(0,0), sys(0,0);
130 Result.MemUsed = getMemUsage();
131 sys::Process::GetTimeUsage(now, user, sys);
133 sys::Process::GetTimeUsage(now, user, sys);
134 Result.MemUsed = getMemUsage();
137 Result.WallTime = now.seconds() + now.microseconds() / 1000000.0;
138 Result.UserTime = user.seconds() + user.microseconds() / 1000000.0;
139 Result.SystemTime = sys.seconds() + sys.microseconds() / 1000000.0;
143 static ManagedStatic<std::vector<Timer*> > ActiveTimers;
145 void Timer::startTimer() {
147 ActiveTimers->push_back(this);
148 Time -= TimeRecord::getCurrentTime(true);
151 void Timer::stopTimer() {
152 Time += TimeRecord::getCurrentTime(false);
154 if (ActiveTimers->back() == this) {
155 ActiveTimers->pop_back();
157 std::vector<Timer*>::iterator I =
158 std::find(ActiveTimers->begin(), ActiveTimers->end(), this);
159 assert(I != ActiveTimers->end() && "stop but no startTimer?");
160 ActiveTimers->erase(I);
164 static void printVal(double Val, double Total, raw_ostream &OS) {
165 if (Total < 1e-7) // Avoid dividing by zero.
168 OS << " " << format("%7.4f", Val) << " (";
169 OS << format("%5.1f", Val*100/Total) << "%)";
173 void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const {
174 if (Total.getUserTime())
175 printVal(getUserTime(), Total.getUserTime(), OS);
176 if (Total.getSystemTime())
177 printVal(getSystemTime(), Total.getSystemTime(), OS);
178 if (Total.getProcessTime())
179 printVal(getProcessTime(), Total.getProcessTime(), OS);
180 printVal(getWallTime(), Total.getWallTime(), OS);
184 if (Total.getMemUsed())
185 OS << format("%9lld", (long long)getMemUsed()) << " ";
189 //===----------------------------------------------------------------------===//
190 // NamedRegionTimer Implementation
191 //===----------------------------------------------------------------------===//
193 typedef StringMap<Timer> Name2TimerMap;
196 StringMap<std::pair<TimerGroup*, Name2TimerMap> > Map;
199 for (StringMap<std::pair<TimerGroup*, Name2TimerMap> >::iterator
200 I = Map.begin(), E = Map.end(); I != E; ++I)
201 delete I->second.first;
204 Timer &get(const std::string &Name, const std::string &GroupName) {
205 sys::SmartScopedLock<true> L(*TimerLock);
207 std::pair<TimerGroup*, Name2TimerMap> &GroupEntry = Map[GroupName];
209 if (!GroupEntry.first)
210 GroupEntry.first = new TimerGroup(GroupName);
212 Timer &T = GroupEntry.second[Name];
213 if (!T.isInitialized())
214 T.init(Name, *GroupEntry.first);
219 static ManagedStatic<Name2TimerMap> NamedTimers;
220 static ManagedStatic<Name2PairMap> NamedGroupedTimers;
222 static Timer &getNamedRegionTimer(const std::string &Name) {
223 sys::SmartScopedLock<true> L(*TimerLock);
225 Timer &T = (*NamedTimers)[Name];
226 if (!T.isInitialized())
231 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
232 : TimeRegion(getNamedRegionTimer(Name)) {}
234 NamedRegionTimer::NamedRegionTimer(const std::string &Name,
235 const std::string &GroupName)
236 : TimeRegion(NamedGroupedTimers->get(Name, GroupName)) {}
238 //===----------------------------------------------------------------------===//
239 // TimerGroup Implementation
240 //===----------------------------------------------------------------------===//
242 TimerGroup::~TimerGroup() {
243 // If the timer group is destroyed before the timers it owns, accumulate and
244 // print the timing data.
245 while (FirstTimer != 0)
246 removeTimer(*FirstTimer);
250 void TimerGroup::removeTimer(Timer &T) {
251 sys::SmartScopedLock<true> L(*TimerLock);
253 // If the timer was started, move its data to TimersToPrint.
255 TimersToPrint.push_back(std::make_pair(T.Time, T.Name));
259 // Unlink the timer from our list.
262 T.Next->Prev = T.Prev;
264 // Print the report when all timers in this group are destroyed if some of
265 // them were started.
266 if (FirstTimer != 0 || TimersToPrint.empty())
269 raw_ostream *OutStream = CreateInfoOutputFile();
270 PrintQueuedTimers(*OutStream);
271 delete OutStream; // Close the file.
274 void TimerGroup::addTimer(Timer &T) {
275 sys::SmartScopedLock<true> L(*TimerLock);
277 // Add the timer to our list.
279 FirstTimer->Prev = &T.Next;
281 T.Prev = &FirstTimer;
285 void TimerGroup::PrintQueuedTimers(raw_ostream &OS) {
286 // Sort the timers in descending order by amount of time taken.
287 std::sort(TimersToPrint.begin(), TimersToPrint.end());
290 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
291 Total += TimersToPrint[i].first;
293 // Print out timing header.
294 OS << "===" << std::string(73, '-') << "===\n";
295 // Figure out how many spaces to indent TimerGroup name.
296 unsigned Padding = (80-Name.length())/2;
297 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
298 OS.indent(Padding) << Name << '\n';
299 OS << "===" << std::string(73, '-') << "===\n";
301 // If this is not an collection of ungrouped times, print the total time.
302 // Ungrouped timers don't really make sense to add up. We still print the
303 // TOTAL line to make the percentages make sense.
304 if (this != DefaultTimerGroup) {
305 OS << " Total Execution Time: ";
306 OS << format("%5.4f", Total.getProcessTime()) << " seconds (";
307 OS << format("%5.4f", Total.getWallTime()) << " wall clock)\n";
311 if (Total.getUserTime())
312 OS << " ---User Time---";
313 if (Total.getSystemTime())
314 OS << " --System Time--";
315 if (Total.getProcessTime())
316 OS << " --User+System--";
317 OS << " ---Wall Time---";
318 if (Total.getMemUsed())
320 OS << " --- Name ---\n";
322 // Loop through all of the timing data, printing it out.
323 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) {
324 const std::pair<TimeRecord, std::string> &Entry = TimersToPrint[e-i-1];
325 Entry.first.print(Total, OS);
326 OS << Entry.second << '\n';
329 Total.print(Total, OS);
333 TimersToPrint.clear();
336 /// print - Print any started timers in this group and zero them.
337 void TimerGroup::print(raw_ostream &OS) {
338 sys::SmartScopedLock<true> L(*TimerLock);
340 // See if any of our timers were started, if so add them to TimersToPrint and
342 for (Timer *T = FirstTimer; T; T = T->Next) {
343 if (!T->Started) continue;
344 TimersToPrint.push_back(std::make_pair(T->Time, T->Name));
346 // Clear out the time.
348 T->Time = TimeRecord();
351 // If any timers were started, print the group.
352 if (!TimersToPrint.empty())
353 PrintQueuedTimers(OS);