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