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 was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source 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/Support/CommandLine.h"
00016 #include "llvm/System/Process.h"
00017 #include <algorithm>
00018 #include <fstream>
00019 #include <functional>
00020 #include <iostream>
00021 #include <map>
00022 using namespace llvm;
00023 
00024 // GetLibSupportInfoOutputFile - Return a file stream to print our output on.
00025 namespace llvm { extern std::ostream *GetLibSupportInfoOutputFile(); }
00026 
00027 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
00028 // of constructor/destructor ordering being unspecified by C++.  Basically the
00029 // problem is that a Statistic<> object gets destroyed, which ends up calling
00030 // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
00031 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
00032 // would get destroyed before the Statistic, causing havoc to ensue.  We "fix"
00033 // this by creating the string the first time it is needed and never destroying
00034 // it.
00035 static std::string &getLibSupportInfoOutputFilename() {
00036   static std::string *LibSupportInfoOutputFilename = new std::string();
00037   return *LibSupportInfoOutputFilename;
00038 }
00039 
00040 namespace {
00041   cl::opt<bool>
00042   TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
00043                                       "tracking (this may be slow)"),
00044              cl::Hidden);
00045 
00046   cl::opt<std::string, true>
00047   InfoOutputFilename("info-output-file", cl::value_desc("filename"),
00048                      cl::desc("File to append -stats and -timer output to"),
00049                    cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
00050 }
00051 
00052 static TimerGroup *DefaultTimerGroup = 0;
00053 static TimerGroup *getDefaultTimerGroup() {
00054   if (DefaultTimerGroup) return DefaultTimerGroup;
00055   return DefaultTimerGroup = new TimerGroup("Miscellaneous Ungrouped Timers");
00056 }
00057 
00058 Timer::Timer(const std::string &N)
00059   : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
00060     Started(false), TG(getDefaultTimerGroup()) {
00061   TG->addTimer();
00062 }
00063 
00064 Timer::Timer(const std::string &N, TimerGroup &tg)
00065   : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N),
00066     Started(false), TG(&tg) {
00067   TG->addTimer();
00068 }
00069 
00070 Timer::Timer(const Timer &T) {
00071   TG = T.TG;
00072   if (TG) TG->addTimer();
00073   operator=(T);
00074 }
00075 
00076 
00077 // Copy ctor, initialize with no TG member.
00078 Timer::Timer(bool, const Timer &T) {
00079   TG = T.TG;     // Avoid assertion in operator=
00080   operator=(T);  // Copy contents
00081   TG = 0;
00082 }
00083 
00084 
00085 Timer::~Timer() {
00086   if (TG) {
00087     if (Started) {
00088       Started = false;
00089       TG->addTimerToPrint(*this);
00090     }
00091     TG->removeTimer();
00092   }
00093 }
00094 
00095 static inline size_t getMemUsage() {
00096   if (TrackSpace)
00097     return sys::Process::GetMallocUsage();
00098   return 0;
00099 }
00100 
00101 struct TimeRecord {
00102   double Elapsed, UserTime, SystemTime;
00103   ssize_t MemUsed;
00104 };
00105 
00106 static TimeRecord getTimeRecord(bool Start) {
00107   TimeRecord Result;
00108 
00109   sys::TimeValue now(0,0);
00110   sys::TimeValue user(0,0);
00111   sys::TimeValue sys(0,0);
00112 
00113   ssize_t MemUsed = 0;
00114   if (Start) {
00115     MemUsed = getMemUsage();
00116     sys::Process::GetTimeUsage(now,user,sys);
00117   } else {
00118     sys::Process::GetTimeUsage(now,user,sys);
00119     MemUsed = getMemUsage();
00120   }
00121 
00122   Result.Elapsed  = now.seconds()  + now.microseconds()  / 1000000.0;
00123   Result.UserTime = user.seconds() + user.microseconds() / 1000000.0;
00124   Result.SystemTime  = sys.seconds()  + sys.microseconds()  / 1000000.0;
00125   Result.MemUsed  = MemUsed;
00126 
00127   return Result;
00128 }
00129 
00130 static std::vector<Timer*> ActiveTimers;
00131 
00132 void Timer::startTimer() {
00133   Started = true;
00134   TimeRecord TR = getTimeRecord(true);
00135   Elapsed    -= TR.Elapsed;
00136   UserTime   -= TR.UserTime;
00137   SystemTime -= TR.SystemTime;
00138   MemUsed    -= TR.MemUsed;
00139   PeakMemBase = TR.MemUsed;
00140   ActiveTimers.push_back(this);
00141 }
00142 
00143 void Timer::stopTimer() {
00144   TimeRecord TR = getTimeRecord(false);
00145   Elapsed    += TR.Elapsed;
00146   UserTime   += TR.UserTime;
00147   SystemTime += TR.SystemTime;
00148   MemUsed    += TR.MemUsed;
00149 
00150   if (ActiveTimers.back() == this) {
00151     ActiveTimers.pop_back();
00152   } else {
00153     std::vector<Timer*>::iterator I =
00154       std::find(ActiveTimers.begin(), ActiveTimers.end(), this);
00155     assert(I != ActiveTimers.end() && "stop but no startTimer?");
00156     ActiveTimers.erase(I);
00157   }
00158 }
00159 
00160 void Timer::sum(const Timer &T) {
00161   Elapsed    += T.Elapsed;
00162   UserTime   += T.UserTime;
00163   SystemTime += T.SystemTime;
00164   MemUsed    += T.MemUsed;
00165   PeakMem    += T.PeakMem;
00166 }
00167 
00168 /// addPeakMemoryMeasurement - This method should be called whenever memory
00169 /// usage needs to be checked.  It adds a peak memory measurement to the
00170 /// currently active timers, which will be printed when the timer group prints
00171 ///
00172 void Timer::addPeakMemoryMeasurement() {
00173   size_t MemUsed = getMemUsage();
00174 
00175   for (std::vector<Timer*>::iterator I = ActiveTimers.begin(),
00176          E = ActiveTimers.end(); I != E; ++I)
00177     (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase);
00178 }
00179 
00180 //===----------------------------------------------------------------------===//
00181 //   NamedRegionTimer Implementation
00182 //===----------------------------------------------------------------------===//
00183 
00184 static Timer &getNamedRegionTimer(const std::string &Name) {
00185   static std::map<std::string, Timer> NamedTimers;
00186 
00187   std::map<std::string, Timer>::iterator I = NamedTimers.lower_bound(Name);
00188   if (I != NamedTimers.end() && I->first == Name)
00189     return I->second;
00190 
00191   return NamedTimers.insert(I, std::make_pair(Name, Timer(Name)))->second;
00192 }
00193 
00194 NamedRegionTimer::NamedRegionTimer(const std::string &Name)
00195   : TimeRegion(getNamedRegionTimer(Name)) {}
00196 
00197 
00198 //===----------------------------------------------------------------------===//
00199 //   TimerGroup Implementation
00200 //===----------------------------------------------------------------------===//
00201 
00202 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the
00203 // TotalWidth size, and B is the AfterDec size.
00204 //
00205 static void printAlignedFP(double Val, unsigned AfterDec, unsigned TotalWidth,
00206                            std::ostream &OS) {
00207   assert(TotalWidth >= AfterDec+1 && "Bad FP Format!");
00208   OS.width(TotalWidth-AfterDec-1);
00209   char OldFill = OS.fill();
00210   OS.fill(' ');
00211   OS << (int)Val;  // Integer part;
00212   OS << ".";
00213   OS.width(AfterDec);
00214   OS.fill('0');
00215   unsigned ResultFieldSize = 1;
00216   while (AfterDec--) ResultFieldSize *= 10;
00217   OS << (int)(Val*ResultFieldSize) % ResultFieldSize;
00218   OS.fill(OldFill);
00219 }
00220 
00221 static void printVal(double Val, double Total, std::ostream &OS) {
00222   if (Total < 1e-7)   // Avoid dividing by zero...
00223     OS << "        -----     ";
00224   else {
00225     OS << "  ";
00226     printAlignedFP(Val, 4, 7, OS);
00227     OS << " (";
00228     printAlignedFP(Val*100/Total, 1, 5, OS);
00229     OS << "%)";
00230   }
00231 }
00232 
00233 void Timer::print(const Timer &Total, std::ostream &OS) {
00234   if (Total.UserTime)
00235     printVal(UserTime, Total.UserTime, OS);
00236   if (Total.SystemTime)
00237     printVal(SystemTime, Total.SystemTime, OS);
00238   if (Total.getProcessTime())
00239     printVal(getProcessTime(), Total.getProcessTime(), OS);
00240   printVal(Elapsed, Total.Elapsed, OS);
00241 
00242   OS << "  ";
00243 
00244   if (Total.MemUsed) {
00245     OS.width(9);
00246     OS << MemUsed << "  ";
00247   }
00248   if (Total.PeakMem) {
00249     if (PeakMem) {
00250       OS.width(9);
00251       OS << PeakMem << "  ";
00252     } else
00253       OS << "           ";
00254   }
00255   OS << Name << "\n";
00256 
00257   Started = false;  // Once printed, don't print again
00258 }
00259 
00260 // GetLibSupportInfoOutputFile - Return a file stream to print our output on...
00261 std::ostream *
00262 llvm::GetLibSupportInfoOutputFile() {
00263   std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename();
00264   if (LibSupportInfoOutputFilename.empty())
00265     return &std::cerr;
00266   if (LibSupportInfoOutputFilename == "-")
00267     return &std::cout;
00268 
00269   std::ostream *Result = new std::ofstream(LibSupportInfoOutputFilename.c_str(),
00270                                            std::ios::app);
00271   if (!Result->good()) {
00272     std::cerr << "Error opening info-output-file '"
00273               << LibSupportInfoOutputFilename << " for appending!\n";
00274     delete Result;
00275     return &std::cerr;
00276   }
00277   return Result;
00278 }
00279 
00280 
00281 void TimerGroup::removeTimer() {
00282   if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report...
00283     // Sort the timers in descending order by amount of time taken...
00284     std::sort(TimersToPrint.begin(), TimersToPrint.end(),
00285               std::greater<Timer>());
00286 
00287     // Figure out how many spaces to indent TimerGroup name...
00288     unsigned Padding = (80-Name.length())/2;
00289     if (Padding > 80) Padding = 0;         // Don't allow "negative" numbers
00290 
00291     std::ostream *OutStream = GetLibSupportInfoOutputFile();
00292 
00293     ++NumTimers;
00294     {  // Scope to contain Total timer... don't allow total timer to drop us to
00295        // zero timers...
00296       Timer Total("TOTAL");
00297 
00298       for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
00299         Total.sum(TimersToPrint[i]);
00300 
00301       // Print out timing header...
00302       *OutStream << "===" << std::string(73, '-') << "===\n"
00303                  << std::string(Padding, ' ') << Name << "\n"
00304                  << "===" << std::string(73, '-')
00305                  << "===\n";
00306 
00307       // If this is not an collection of ungrouped times, print the total time.
00308       // Ungrouped timers don't really make sense to add up.  We still print the
00309       // TOTAL line to make the percentages make sense.
00310       if (this != DefaultTimerGroup) {
00311         *OutStream << "  Total Execution Time: ";
00312 
00313         printAlignedFP(Total.getProcessTime(), 4, 5, *OutStream);
00314         *OutStream << " seconds (";
00315         printAlignedFP(Total.getWallTime(), 4, 5, *OutStream);
00316         *OutStream << " wall clock)\n";
00317       }
00318       *OutStream << "\n";
00319 
00320       if (Total.UserTime)
00321         *OutStream << "   ---User Time---";
00322       if (Total.SystemTime)
00323         *OutStream << "   --System Time--";
00324       if (Total.getProcessTime())
00325         *OutStream << "   --User+System--";
00326       *OutStream << "   ---Wall Time---";
00327       if (Total.getMemUsed())
00328         *OutStream << "  ---Mem---";
00329       if (Total.getPeakMem())
00330         *OutStream << "  -PeakMem-";
00331       *OutStream << "  --- Name ---\n";
00332 
00333       // Loop through all of the timing data, printing it out...
00334       for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
00335         TimersToPrint[i].print(Total, *OutStream);
00336 
00337       Total.print(Total, *OutStream);
00338       *OutStream << std::endl;  // Flush output
00339     }
00340     --NumTimers;
00341 
00342     TimersToPrint.clear();
00343 
00344     if (OutStream != &std::cerr && OutStream != &std::cout)
00345       delete OutStream;   // Close the file...
00346   }
00347 
00348   // Delete default timer group!
00349   if (NumTimers == 0 && this == DefaultTimerGroup) {
00350     delete DefaultTimerGroup;
00351     DefaultTimerGroup = 0;
00352   }
00353 }
00354