1 //===-- Timer.cpp - Interval Timing Support -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file was developed by the LLVM research group and is distributed under 6 // the University of Illinois Open Source License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Interval Timing implementation. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Support/Timer.h" 15 #include "llvm/Support/CommandLine.h" 16 #include "llvm/System/Process.h" 17 #include <algorithm> 18 #include <fstream> 19 #include <functional> 20 #include <iostream> 21 #include <map> 22 using namespace llvm; 23 24 // GetLibSupportInfoOutputFile - Return a file stream to print our output on. 25 namespace llvm { extern std::ostream *GetLibSupportInfoOutputFile(); } 26 27 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy 28 // of constructor/destructor ordering being unspecified by C++. Basically the 29 // problem is that a Statistic<> object gets destroyed, which ends up calling 30 // 'GetLibSupportInfoOutputFile()' (below), which calls this function. 31 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it 32 // would get destroyed before the Statistic, causing havoc to ensue. We "fix" 33 // this by creating the string the first time it is needed and never destroying 34 // it. 35 static std::string &getLibSupportInfoOutputFilename() { 36 static std::string *LibSupportInfoOutputFilename = new std::string(); 37 return *LibSupportInfoOutputFilename; 38 } 39 40 namespace { 41 cl::opt<bool> 42 TrackSpace("track-memory", cl::desc("Enable -time-passes memory " 43 "tracking (this may be slow)"), 44 cl::Hidden); 45 46 cl::opt<std::string, true> 47 InfoOutputFilename("info-output-file", cl::value_desc("filename"), 48 cl::desc("File to append -stats and -timer output to"), 49 cl::Hidden, cl::location(getLibSupportInfoOutputFilename())); 50 } 51 52 static TimerGroup *DefaultTimerGroup = 0; 53 static TimerGroup *getDefaultTimerGroup() { 54 if (DefaultTimerGroup) return DefaultTimerGroup; 55 return DefaultTimerGroup = new TimerGroup("Miscellaneous Ungrouped Timers"); 56 } 57 58 Timer::Timer(const std::string &N) 59 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N), 60 Started(false), TG(getDefaultTimerGroup()) { 61 TG->addTimer(); 62 } 63 64 Timer::Timer(const std::string &N, TimerGroup &tg) 65 : Elapsed(0), UserTime(0), SystemTime(0), MemUsed(0), PeakMem(0), Name(N), 66 Started(false), TG(&tg) { 67 TG->addTimer(); 68 } 69 70 Timer::Timer(const Timer &T) { 71 TG = T.TG; 72 if (TG) TG->addTimer(); 73 operator=(T); 74 } 75 76 77 // Copy ctor, initialize with no TG member. 78 Timer::Timer(bool, const Timer &T) { 79 TG = T.TG; // Avoid assertion in operator= 80 operator=(T); // Copy contents 81 TG = 0; 82 } 83 84 85 Timer::~Timer() { 86 if (TG) { 87 if (Started) { 88 Started = false; 89 TG->addTimerToPrint(*this); 90 } 91 TG->removeTimer(); 92 } 93 } 94 95 static inline size_t getMemUsage() { 96 if (TrackSpace) 97 return sys::Process::GetMallocUsage(); 98 return 0; 99 } 100 101 struct TimeRecord { 102 double Elapsed, UserTime, SystemTime; 103 ssize_t MemUsed; 104 }; 105 106 static TimeRecord getTimeRecord(bool Start) { 107 TimeRecord Result; 108 109 sys::TimeValue now(0,0); 110 sys::TimeValue user(0,0); 111 sys::TimeValue sys(0,0); 112 113 ssize_t MemUsed = 0; 114 if (Start) { 115 sys::Process::GetTimeUsage(now,user,sys); 116 MemUsed = getMemUsage(); 117 } else { 118 MemUsed = getMemUsage(); 119 sys::Process::GetTimeUsage(now,user,sys); 120 } 121 122 Result.Elapsed = now.seconds() + now.microseconds() / 1000000.0; 123 Result.UserTime = user.seconds() + user.microseconds() / 1000000.0; 124 Result.SystemTime = sys.seconds() + sys.microseconds() / 1000000.0; 125 Result.MemUsed = MemUsed; 126 127 return Result; 128 } 129 130 static std::vector<Timer*> ActiveTimers; 131 132 void Timer::startTimer() { 133 Started = true; 134 TimeRecord TR = getTimeRecord(true); 135 Elapsed -= TR.Elapsed; 136 UserTime -= TR.UserTime; 137 SystemTime -= TR.SystemTime; 138 MemUsed -= TR.MemUsed; 139 PeakMemBase = TR.MemUsed; 140 ActiveTimers.push_back(this); 141 } 142 143 void Timer::stopTimer() { 144 TimeRecord TR = getTimeRecord(false); 145 Elapsed += TR.Elapsed; 146 UserTime += TR.UserTime; 147 SystemTime += TR.SystemTime; 148 MemUsed += TR.MemUsed; 149 150 if (ActiveTimers.back() == this) { 151 ActiveTimers.pop_back(); 152 } else { 153 std::vector<Timer*>::iterator I = 154 std::find(ActiveTimers.begin(), ActiveTimers.end(), this); 155 assert(I != ActiveTimers.end() && "stop but no startTimer?"); 156 ActiveTimers.erase(I); 157 } 158 } 159 160 void Timer::sum(const Timer &T) { 161 Elapsed += T.Elapsed; 162 UserTime += T.UserTime; 163 SystemTime += T.SystemTime; 164 MemUsed += T.MemUsed; 165 PeakMem += T.PeakMem; 166 } 167 168 /// addPeakMemoryMeasurement - This method should be called whenever memory 169 /// usage needs to be checked. It adds a peak memory measurement to the 170 /// currently active timers, which will be printed when the timer group prints 171 /// 172 void Timer::addPeakMemoryMeasurement() { 173 size_t MemUsed = getMemUsage(); 174 175 for (std::vector<Timer*>::iterator I = ActiveTimers.begin(), 176 E = ActiveTimers.end(); I != E; ++I) 177 (*I)->PeakMem = std::max((*I)->PeakMem, MemUsed-(*I)->PeakMemBase); 178 } 179 180 //===----------------------------------------------------------------------===// 181 // NamedRegionTimer Implementation 182 //===----------------------------------------------------------------------===// 183 184 static Timer &getNamedRegionTimer(const std::string &Name) { 185 static std::map<std::string, Timer> NamedTimers; 186 187 std::map<std::string, Timer>::iterator I = NamedTimers.lower_bound(Name); 188 if (I != NamedTimers.end() && I->first == Name) 189 return I->second; 190 191 return NamedTimers.insert(I, std::make_pair(Name, Timer(Name)))->second; 192 } 193 194 NamedRegionTimer::NamedRegionTimer(const std::string &Name) 195 : TimeRegion(getNamedRegionTimer(Name)) {} 196 197 198 //===----------------------------------------------------------------------===// 199 // TimerGroup Implementation 200 //===----------------------------------------------------------------------===// 201 202 // printAlignedFP - Simulate the printf "%A.Bf" format, where A is the 203 // TotalWidth size, and B is the AfterDec size. 204 // 205 static void printAlignedFP(double Val, unsigned AfterDec, unsigned TotalWidth, 206 std::ostream &OS) { 207 assert(TotalWidth >= AfterDec+1 && "Bad FP Format!"); 208 OS.width(TotalWidth-AfterDec-1); 209 char OldFill = OS.fill(); 210 OS.fill(' '); 211 OS << (int)Val; // Integer part; 212 OS << "."; 213 OS.width(AfterDec); 214 OS.fill('0'); 215 unsigned ResultFieldSize = 1; 216 while (AfterDec--) ResultFieldSize *= 10; 217 OS << (int)(Val*ResultFieldSize) % ResultFieldSize; 218 OS.fill(OldFill); 219 } 220 221 static void printVal(double Val, double Total, std::ostream &OS) { 222 if (Total < 1e-7) // Avoid dividing by zero... 223 OS << " ----- "; 224 else { 225 OS << " "; 226 printAlignedFP(Val, 4, 7, OS); 227 OS << " ("; 228 printAlignedFP(Val*100/Total, 1, 5, OS); 229 OS << "%)"; 230 } 231 } 232 233 void Timer::print(const Timer &Total, std::ostream &OS) { 234 if (Total.UserTime) 235 printVal(UserTime, Total.UserTime, OS); 236 if (Total.SystemTime) 237 printVal(SystemTime, Total.SystemTime, OS); 238 if (Total.getProcessTime()) 239 printVal(getProcessTime(), Total.getProcessTime(), OS); 240 printVal(Elapsed, Total.Elapsed, OS); 241 242 OS << " "; 243 244 if (Total.MemUsed) { 245 OS.width(9); 246 OS << MemUsed << " "; 247 } 248 if (Total.PeakMem) { 249 if (PeakMem) { 250 OS.width(9); 251 OS << PeakMem << " "; 252 } else 253 OS << " "; 254 } 255 OS << Name << "\n"; 256 257 Started = false; // Once printed, don't print again 258 } 259 260 // GetLibSupportInfoOutputFile - Return a file stream to print our output on... 261 std::ostream * 262 llvm::GetLibSupportInfoOutputFile() { 263 std::string &LibSupportInfoOutputFilename = getLibSupportInfoOutputFilename(); 264 if (LibSupportInfoOutputFilename.empty()) 265 return &std::cerr; 266 if (LibSupportInfoOutputFilename == "-") 267 return &std::cout; 268 269 std::ostream *Result = new std::ofstream(LibSupportInfoOutputFilename.c_str(), 270 std::ios::app); 271 if (!Result->good()) { 272 std::cerr << "Error opening info-output-file '" 273 << LibSupportInfoOutputFilename << " for appending!\n"; 274 delete Result; 275 return &std::cerr; 276 } 277 return Result; 278 } 279 280 281 void TimerGroup::removeTimer() { 282 if (--NumTimers == 0 && !TimersToPrint.empty()) { // Print timing report... 283 // Sort the timers in descending order by amount of time taken... 284 std::sort(TimersToPrint.begin(), TimersToPrint.end(), 285 std::greater<Timer>()); 286 287 // Figure out how many spaces to indent TimerGroup name... 288 unsigned Padding = (80-Name.length())/2; 289 if (Padding > 80) Padding = 0; // Don't allow "negative" numbers 290 291 std::ostream *OutStream = GetLibSupportInfoOutputFile(); 292 293 ++NumTimers; 294 { // Scope to contain Total timer... don't allow total timer to drop us to 295 // zero timers... 296 Timer Total("TOTAL"); 297 298 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) 299 Total.sum(TimersToPrint[i]); 300 301 // Print out timing header... 302 *OutStream << "===" << std::string(73, '-') << "===\n" 303 << std::string(Padding, ' ') << Name << "\n" 304 << "===" << std::string(73, '-') 305 << "===\n Total Execution Time: "; 306 307 printAlignedFP(Total.getProcessTime(), 4, 5, *OutStream); 308 *OutStream << " seconds ("; 309 printAlignedFP(Total.getWallTime(), 4, 5, *OutStream); 310 *OutStream << " wall clock)\n\n"; 311 312 if (Total.UserTime) 313 *OutStream << " ---User Time---"; 314 if (Total.SystemTime) 315 *OutStream << " --System Time--"; 316 if (Total.getProcessTime()) 317 *OutStream << " --User+System--"; 318 *OutStream << " ---Wall Time---"; 319 if (Total.getMemUsed()) 320 *OutStream << " ---Mem---"; 321 if (Total.getPeakMem()) 322 *OutStream << " -PeakMem-"; 323 *OutStream << " --- Name ---\n"; 324 325 // Loop through all of the timing data, printing it out... 326 for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) 327 TimersToPrint[i].print(Total, *OutStream); 328 329 Total.print(Total, *OutStream); 330 *OutStream << std::endl; // Flush output 331 } 332 --NumTimers; 333 334 TimersToPrint.clear(); 335 336 if (OutStream != &std::cerr && OutStream != &std::cout) 337 delete OutStream; // Close the file... 338 } 339 340 // Delete default timer group! 341 if (NumTimers == 0 && this == DefaultTimerGroup) { 342 delete DefaultTimerGroup; 343 DefaultTimerGroup = 0; 344 } 345 } 346 347