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/StringMap.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 // GetLibSupportInfoOutputFile - Return a file stream to print our output on.
57 raw_ostream *llvm::GetLibSupportInfoOutputFile() {
58 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
59 if (LibSupportInfoOutputFilename.empty())
61 if (LibSupportInfoOutputFilename == "-")
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";
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.
120 TG->addTimerToPrint(Time, Name);
125 static inline size_t getMemUsage() {
127 return sys::Process::GetMallocUsage();
131 TimeRecord TimeRecord::getCurrentTime(bool Start) {
134 sys::TimeValue now(0,0);
135 sys::TimeValue user(0,0);
136 sys::TimeValue sys(0,0);
140 MemUsed = getMemUsage();
141 sys::Process::GetTimeUsage(now, user, sys);
143 sys::Process::GetTimeUsage(now, user, sys);
144 MemUsed = getMemUsage();
147 Result.WallTime = now.seconds() + now.microseconds() / 1000000.0;
148 Result.UserTime = user.seconds() + user.microseconds() / 1000000.0;
149 Result.SystemTime = sys.seconds() + sys.microseconds() / 1000000.0;
150 Result.MemUsed = MemUsed;
154 static ManagedStatic<std::vector<Timer*> > ActiveTimers;
156 void Timer::startTimer() {
158 ActiveTimers->push_back(this);
159 Time -= TimeRecord::getCurrentTime(true);
162 void Timer::stopTimer() {
163 Time += TimeRecord::getCurrentTime(false);
165 if (ActiveTimers->back() == this) {
166 ActiveTimers->pop_back();
168 std::vector<Timer*>::iterator I =
169 std::find(ActiveTimers->begin(), ActiveTimers->end(), this);
170 assert(I != ActiveTimers->end() && "stop but no startTimer?");
171 ActiveTimers->erase(I);
175 static void printVal(double Val, double Total, raw_ostream &OS) {
176 if (Total < 1e-7) // Avoid dividing by zero.
179 OS << " " << format("%7.4f", Val) << " (";
180 OS << format("%5.1f", Val*100/Total) << "%)";
184 void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const {
185 if (Total.getUserTime())
186 printVal(getUserTime(), Total.getUserTime(), OS);
187 if (Total.getSystemTime())
188 printVal(getSystemTime(), Total.getSystemTime(), OS);
189 if (Total.getProcessTime())
190 printVal(getProcessTime(), Total.getProcessTime(), OS);
191 printVal(getWallTime(), Total.getWallTime(), OS);
195 if (Total.getMemUsed())
196 OS << format("%9lld", (long long)getMemUsed()) << " ";
200 //===----------------------------------------------------------------------===//
201 // NamedRegionTimer Implementation
202 //===----------------------------------------------------------------------===//
204 typedef StringMap<Timer> Name2TimerMap;
205 typedef StringMap<std::pair<TimerGroup, Name2TimerMap> > Name2PairMap;
207 static ManagedStatic<Name2TimerMap> NamedTimers;
208 static ManagedStatic<Name2PairMap> NamedGroupedTimers;
210 static Timer &getNamedRegionTimer(const std::string &Name) {
211 sys::SmartScopedLock<true> L(*TimerLock);
213 Timer &T = (*NamedTimers)[Name];
214 if (!T.isInitialized())
219 static Timer &getNamedRegionTimer(const std::string &Name,
220 const std::string &GroupName) {
221 sys::SmartScopedLock<true> L(*TimerLock);
223 std::pair<TimerGroup, Name2TimerMap> &GroupEntry =
224 (*NamedGroupedTimers)[GroupName];
226 if (GroupEntry.second.empty())
227 GroupEntry.first.setName(GroupName);
229 Timer &T = GroupEntry.second[Name];
230 if (!T.isInitialized())
235 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
236 : TimeRegion(getNamedRegionTimer(Name)) {}
238 NamedRegionTimer::NamedRegionTimer(const std::string &Name,
239 const std::string &GroupName)
240 : TimeRegion(getNamedRegionTimer(Name, GroupName)) {}
242 //===----------------------------------------------------------------------===//
243 // TimerGroup Implementation
244 //===----------------------------------------------------------------------===//
246 void TimerGroup::removeTimer() {
247 sys::SmartScopedLock<true> L(*TimerLock);
248 if (--NumTimers != 0 || TimersToPrint.empty())
249 return; // Don't print timing report.
251 // Sort the timers in descending order by amount of time taken.
252 std::sort(TimersToPrint.begin(), TimersToPrint.end());
254 // Figure out how many spaces to indent TimerGroup name.
255 unsigned Padding = (80-Name.length())/2;
256 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
258 raw_ostream *OutStream = GetLibSupportInfoOutputFile();
261 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
262 Total += TimersToPrint[i].first;
264 // Print out timing header.
265 *OutStream << "===" << std::string(73, '-') << "===\n";
266 OutStream->indent(Padding) << Name << '\n';
267 *OutStream << "===" << std::string(73, '-') << "===\n";
269 // If this is not an collection of ungrouped times, print the total time.
270 // Ungrouped timers don't really make sense to add up. We still print the
271 // TOTAL line to make the percentages make sense.
272 if (this != DefaultTimerGroup) {
273 *OutStream << " Total Execution Time: ";
274 *OutStream << format("%5.4f", Total.getProcessTime()) << " seconds (";
275 *OutStream << format("%5.4f", Total.getWallTime()) << " wall clock)\n";
279 if (Total.getUserTime())
280 *OutStream << " ---User Time---";
281 if (Total.getSystemTime())
282 *OutStream << " --System Time--";
283 if (Total.getProcessTime())
284 *OutStream << " --User+System--";
285 *OutStream << " ---Wall Time---";
286 if (Total.getMemUsed())
287 *OutStream << " ---Mem---";
288 *OutStream << " --- Name ---\n";
290 // Loop through all of the timing data, printing it out.
291 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) {
292 const std::pair<TimeRecord, std::string> &Entry = TimersToPrint[e-i-1];
293 Entry.first.print(Total, *OutStream);
294 *OutStream << Entry.second << '\n';
297 Total.print(Total, *OutStream);
298 *OutStream << "Total\n\n";
301 TimersToPrint.clear();
303 if (OutStream != &errs() && OutStream != &outs())
304 delete OutStream; // Close the file.
307 void TimerGroup::addTimer() {
308 sys::SmartScopedLock<true> L(*TimerLock);
312 void TimerGroup::addTimerToPrint(const TimeRecord &T, const std::string &Name) {
313 sys::SmartScopedLock<true> L(*TimerLock);
314 TimersToPrint.push_back(std::make_pair(T, Name));