LLVM API Documentation

Timer.cpp
Go to the documentation of this file.
00001 //===-- Timer.cpp - Interval Timing Support -------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Interval Timing implementation.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Support/Timer.h"
00015 #include "llvm/ADT/StringMap.h"
00016 #include "llvm/Support/CommandLine.h"
00017 #include "llvm/Support/Debug.h"
00018 #include "llvm/Support/Format.h"
00019 #include "llvm/Support/ManagedStatic.h"
00020 #include "llvm/Support/Mutex.h"
00021 #include "llvm/Support/Process.h"
00022 #include "llvm/Support/raw_ostream.h"
00023 using namespace llvm;
00024 
00025 // CreateInfoOutputFile - Return a file stream to print our output on.
00026 namespace llvm { extern raw_ostream *CreateInfoOutputFile(); }
00027 
00028 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
00029 // of constructor/destructor ordering being unspecified by C++.  Basically the
00030 // problem is that a Statistic object gets destroyed, which ends up calling
00031 // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
00032 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
00033 // would get destroyed before the Statistic, causing havoc to ensue.  We "fix"
00034 // this by creating the string the first time it is needed and never destroying
00035 // it.
00036 static ManagedStatic<std::string> LibSupportInfoOutputFilename;
00037 static std::string &getLibSupportInfoOutputFilename() {
00038   return *LibSupportInfoOutputFilename;
00039 }
00040 
00041 static ManagedStatic<sys::SmartMutex<true> > TimerLock;
00042 
00043 namespace {
00044   static cl::opt<bool>
00045   TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
00046                                       "tracking (this may be slow)"),
00047              cl::Hidden);
00048 
00049   static cl::opt<std::string, true>
00050   InfoOutputFilename("info-output-file", cl::value_desc("filename"),
00051                      cl::desc("File to append -stats and -timer output to"),
00052                    cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
00053 }
00054 
00055 // CreateInfoOutputFile - Return a file stream to print our output on.
00056 raw_ostream *llvm::CreateInfoOutputFile() {
00057   const std::string &OutputFilename = getLibSupportInfoOutputFilename();
00058   if (OutputFilename.empty())
00059     return new raw_fd_ostream(2, false); // stderr.
00060   if (OutputFilename == "-")
00061     return new raw_fd_ostream(1, false); // stdout.
00062   
00063   // Append mode is used because the info output file is opened and closed
00064   // each time -stats or -time-passes wants to print output to it. To
00065   // compensate for this, the test-suite Makefiles have code to delete the
00066   // info output file before running commands which write to it.
00067   std::string Error;
00068   raw_ostream *Result = new raw_fd_ostream(
00069       OutputFilename.c_str(), Error, sys::fs::F_Append | sys::fs::F_Text);
00070   if (Error.empty())
00071     return Result;
00072   
00073   errs() << "Error opening info-output-file '"
00074     << OutputFilename << " for appending!\n";
00075   delete Result;
00076   return new raw_fd_ostream(2, false); // stderr.
00077 }
00078 
00079 
00080 static TimerGroup *DefaultTimerGroup = nullptr;
00081 static TimerGroup *getDefaultTimerGroup() {
00082   TimerGroup *tmp = DefaultTimerGroup;
00083   sys::MemoryFence();
00084   if (tmp) return tmp;
00085   
00086   llvm_acquire_global_lock();
00087   tmp = DefaultTimerGroup;
00088   if (!tmp) {
00089     tmp = new TimerGroup("Miscellaneous Ungrouped Timers");
00090     sys::MemoryFence();
00091     DefaultTimerGroup = tmp;
00092   }
00093   llvm_release_global_lock();
00094 
00095   return tmp;
00096 }
00097 
00098 //===----------------------------------------------------------------------===//
00099 // Timer Implementation
00100 //===----------------------------------------------------------------------===//
00101 
00102 void Timer::init(StringRef N) {
00103   assert(!TG && "Timer already initialized");
00104   Name.assign(N.begin(), N.end());
00105   Started = false;
00106   TG = getDefaultTimerGroup();
00107   TG->addTimer(*this);
00108 }
00109 
00110 void Timer::init(StringRef N, TimerGroup &tg) {
00111   assert(!TG && "Timer already initialized");
00112   Name.assign(N.begin(), N.end());
00113   Started = false;
00114   TG = &tg;
00115   TG->addTimer(*this);
00116 }
00117 
00118 Timer::~Timer() {
00119   if (!TG) return;  // Never initialized, or already cleared.
00120   TG->removeTimer(*this);
00121 }
00122 
00123 static inline size_t getMemUsage() {
00124   if (!TrackSpace) return 0;
00125   return sys::Process::GetMallocUsage();
00126 }
00127 
00128 TimeRecord TimeRecord::getCurrentTime(bool Start) {
00129   TimeRecord Result;
00130   sys::TimeValue now(0,0), user(0,0), sys(0,0);
00131   
00132   if (Start) {
00133     Result.MemUsed = getMemUsage();
00134     sys::Process::GetTimeUsage(now, user, sys);
00135   } else {
00136     sys::Process::GetTimeUsage(now, user, sys);
00137     Result.MemUsed = getMemUsage();
00138   }
00139 
00140   Result.WallTime   =  now.seconds() +  now.microseconds() / 1000000.0;
00141   Result.UserTime   = user.seconds() + user.microseconds() / 1000000.0;
00142   Result.SystemTime =  sys.seconds() +  sys.microseconds() / 1000000.0;
00143   return Result;
00144 }
00145 
00146 static ManagedStatic<std::vector<Timer*> > ActiveTimers;
00147 
00148 void Timer::startTimer() {
00149   Started = true;
00150   ActiveTimers->push_back(this);
00151   Time -= TimeRecord::getCurrentTime(true);
00152 }
00153 
00154 void Timer::stopTimer() {
00155   Time += TimeRecord::getCurrentTime(false);
00156 
00157   if (ActiveTimers->back() == this) {
00158     ActiveTimers->pop_back();
00159   } else {
00160     std::vector<Timer*>::iterator I =
00161       std::find(ActiveTimers->begin(), ActiveTimers->end(), this);
00162     assert(I != ActiveTimers->end() && "stop but no startTimer?");
00163     ActiveTimers->erase(I);
00164   }
00165 }
00166 
00167 static void printVal(double Val, double Total, raw_ostream &OS) {
00168   if (Total < 1e-7)   // Avoid dividing by zero.
00169     OS << "        -----     ";
00170   else
00171     OS << format("  %7.4f (%5.1f%%)", Val, Val*100/Total);
00172 }
00173 
00174 void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const {
00175   if (Total.getUserTime())
00176     printVal(getUserTime(), Total.getUserTime(), OS);
00177   if (Total.getSystemTime())
00178     printVal(getSystemTime(), Total.getSystemTime(), OS);
00179   if (Total.getProcessTime())
00180     printVal(getProcessTime(), Total.getProcessTime(), OS);
00181   printVal(getWallTime(), Total.getWallTime(), OS);
00182   
00183   OS << "  ";
00184   
00185   if (Total.getMemUsed())
00186     OS << format("%9" PRId64 "  ", (int64_t)getMemUsed());
00187 }
00188 
00189 
00190 //===----------------------------------------------------------------------===//
00191 //   NamedRegionTimer Implementation
00192 //===----------------------------------------------------------------------===//
00193 
00194 namespace {
00195 
00196 typedef StringMap<Timer> Name2TimerMap;
00197 
00198 class Name2PairMap {
00199   StringMap<std::pair<TimerGroup*, Name2TimerMap> > Map;
00200 public:
00201   ~Name2PairMap() {
00202     for (StringMap<std::pair<TimerGroup*, Name2TimerMap> >::iterator
00203          I = Map.begin(), E = Map.end(); I != E; ++I)
00204       delete I->second.first;
00205   }
00206   
00207   Timer &get(StringRef Name, StringRef GroupName) {
00208     sys::SmartScopedLock<true> L(*TimerLock);
00209     
00210     std::pair<TimerGroup*, Name2TimerMap> &GroupEntry = Map[GroupName];
00211     
00212     if (!GroupEntry.first)
00213       GroupEntry.first = new TimerGroup(GroupName);
00214     
00215     Timer &T = GroupEntry.second[Name];
00216     if (!T.isInitialized())
00217       T.init(Name, *GroupEntry.first);
00218     return T;
00219   }
00220 };
00221 
00222 }
00223 
00224 static ManagedStatic<Name2TimerMap> NamedTimers;
00225 static ManagedStatic<Name2PairMap> NamedGroupedTimers;
00226 
00227 static Timer &getNamedRegionTimer(StringRef Name) {
00228   sys::SmartScopedLock<true> L(*TimerLock);
00229   
00230   Timer &T = (*NamedTimers)[Name];
00231   if (!T.isInitialized())
00232     T.init(Name);
00233   return T;
00234 }
00235 
00236 NamedRegionTimer::NamedRegionTimer(StringRef Name,
00237                                    bool Enabled)
00238   : TimeRegion(!Enabled ? nullptr : &getNamedRegionTimer(Name)) {}
00239 
00240 NamedRegionTimer::NamedRegionTimer(StringRef Name, StringRef GroupName,
00241                                    bool Enabled)
00242   : TimeRegion(!Enabled ? nullptr : &NamedGroupedTimers->get(Name, GroupName)){}
00243 
00244 //===----------------------------------------------------------------------===//
00245 //   TimerGroup Implementation
00246 //===----------------------------------------------------------------------===//
00247 
00248 /// TimerGroupList - This is the global list of TimerGroups, maintained by the
00249 /// TimerGroup ctor/dtor and is protected by the TimerLock lock.
00250 static TimerGroup *TimerGroupList = nullptr;
00251 
00252 TimerGroup::TimerGroup(StringRef name)
00253   : Name(name.begin(), name.end()), FirstTimer(nullptr) {
00254     
00255   // Add the group to TimerGroupList.
00256   sys::SmartScopedLock<true> L(*TimerLock);
00257   if (TimerGroupList)
00258     TimerGroupList->Prev = &Next;
00259   Next = TimerGroupList;
00260   Prev = &TimerGroupList;
00261   TimerGroupList = this;
00262 }
00263 
00264 TimerGroup::~TimerGroup() {
00265   // If the timer group is destroyed before the timers it owns, accumulate and
00266   // print the timing data.
00267   while (FirstTimer)
00268     removeTimer(*FirstTimer);
00269   
00270   // Remove the group from the TimerGroupList.
00271   sys::SmartScopedLock<true> L(*TimerLock);
00272   *Prev = Next;
00273   if (Next)
00274     Next->Prev = Prev;
00275 }
00276 
00277 
00278 void TimerGroup::removeTimer(Timer &T) {
00279   sys::SmartScopedLock<true> L(*TimerLock);
00280   
00281   // If the timer was started, move its data to TimersToPrint.
00282   if (T.Started)
00283     TimersToPrint.push_back(std::make_pair(T.Time, T.Name));
00284 
00285   T.TG = nullptr;
00286   
00287   // Unlink the timer from our list.
00288   *T.Prev = T.Next;
00289   if (T.Next)
00290     T.Next->Prev = T.Prev;
00291   
00292   // Print the report when all timers in this group are destroyed if some of
00293   // them were started.
00294   if (FirstTimer || TimersToPrint.empty())
00295     return;
00296   
00297   raw_ostream *OutStream = CreateInfoOutputFile();
00298   PrintQueuedTimers(*OutStream);
00299   delete OutStream;   // Close the file.
00300 }
00301 
00302 void TimerGroup::addTimer(Timer &T) {
00303   sys::SmartScopedLock<true> L(*TimerLock);
00304   
00305   // Add the timer to our list.
00306   if (FirstTimer)
00307     FirstTimer->Prev = &T.Next;
00308   T.Next = FirstTimer;
00309   T.Prev = &FirstTimer;
00310   FirstTimer = &T;
00311 }
00312 
00313 void TimerGroup::PrintQueuedTimers(raw_ostream &OS) {
00314   // Sort the timers in descending order by amount of time taken.
00315   std::sort(TimersToPrint.begin(), TimersToPrint.end());
00316   
00317   TimeRecord Total;
00318   for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
00319     Total += TimersToPrint[i].first;
00320   
00321   // Print out timing header.
00322   OS << "===" << std::string(73, '-') << "===\n";
00323   // Figure out how many spaces to indent TimerGroup name.
00324   unsigned Padding = (80-Name.length())/2;
00325   if (Padding > 80) Padding = 0;         // Don't allow "negative" numbers
00326   OS.indent(Padding) << Name << '\n';
00327   OS << "===" << std::string(73, '-') << "===\n";
00328   
00329   // If this is not an collection of ungrouped times, print the total time.
00330   // Ungrouped timers don't really make sense to add up.  We still print the
00331   // TOTAL line to make the percentages make sense.
00332   if (this != DefaultTimerGroup)
00333     OS << format("  Total Execution Time: %5.4f seconds (%5.4f wall clock)\n",
00334                  Total.getProcessTime(), Total.getWallTime());
00335   OS << '\n';
00336   
00337   if (Total.getUserTime())
00338     OS << "   ---User Time---";
00339   if (Total.getSystemTime())
00340     OS << "   --System Time--";
00341   if (Total.getProcessTime())
00342     OS << "   --User+System--";
00343   OS << "   ---Wall Time---";
00344   if (Total.getMemUsed())
00345     OS << "  ---Mem---";
00346   OS << "  --- Name ---\n";
00347   
00348   // Loop through all of the timing data, printing it out.
00349   for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) {
00350     const std::pair<TimeRecord, std::string> &Entry = TimersToPrint[e-i-1];
00351     Entry.first.print(Total, OS);
00352     OS << Entry.second << '\n';
00353   }
00354   
00355   Total.print(Total, OS);
00356   OS << "Total\n\n";
00357   OS.flush();
00358   
00359   TimersToPrint.clear();
00360 }
00361 
00362 /// print - Print any started timers in this group and zero them.
00363 void TimerGroup::print(raw_ostream &OS) {
00364   sys::SmartScopedLock<true> L(*TimerLock);
00365 
00366   // See if any of our timers were started, if so add them to TimersToPrint and
00367   // reset them.
00368   for (Timer *T = FirstTimer; T; T = T->Next) {
00369     if (!T->Started) continue;
00370     TimersToPrint.push_back(std::make_pair(T->Time, T->Name));
00371     
00372     // Clear out the time.
00373     T->Started = 0;
00374     T->Time = TimeRecord();
00375   }
00376 
00377   // If any timers were started, print the group.
00378   if (!TimersToPrint.empty())
00379     PrintQueuedTimers(OS);
00380 }
00381 
00382 /// printAll - This static method prints all timers and clears them all out.
00383 void TimerGroup::printAll(raw_ostream &OS) {
00384   sys::SmartScopedLock<true> L(*TimerLock);
00385 
00386   for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
00387     TG->print(OS);
00388 }