Timer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. #include "llvm/Support/Timer.h"
  14. #include "llvm/Support/CommandLine.h"
  15. #include "llvm/Support/Debug.h"
  16. #include "llvm/Support/ManagedStatic.h"
  17. #include "llvm/Support/raw_ostream.h"
  18. #include "llvm/Support/Format.h"
  19. #include "llvm/Support/Mutex.h"
  20. #include "llvm/Support/Process.h"
  21. #include "llvm/ADT/OwningPtr.h"
  22. #include "llvm/ADT/StringMap.h"
  23. using namespace llvm;
  24. // CreateInfoOutputFile - Return a file stream to print our output on.
  25. namespace llvm { extern raw_ostream *CreateInfoOutputFile(); }
  26. // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
  27. // of constructor/destructor ordering being unspecified by C++. Basically the
  28. // problem is that a Statistic object gets destroyed, which ends up calling
  29. // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
  30. // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
  31. // would get destroyed before the Statistic, causing havoc to ensue. We "fix"
  32. // this by creating the string the first time it is needed and never destroying
  33. // it.
  34. static ManagedStatic<std::string> LibSupportInfoOutputFilename;
  35. static std::string &getLibSupportInfoOutputFilename() {
  36. return *LibSupportInfoOutputFilename;
  37. }
  38. static ManagedStatic<sys::SmartMutex<true> > TimerLock;
  39. namespace {
  40. static cl::opt<bool>
  41. TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
  42. "tracking (this may be slow)"),
  43. cl::Hidden);
  44. static cl::opt<std::string, true>
  45. InfoOutputFilename("info-output-file", cl::value_desc("filename"),
  46. cl::desc("File to append -stats and -timer output to"),
  47. cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
  48. }
  49. // CreateInfoOutputFile - Return a file stream to print our output on.
  50. raw_ostream *llvm::CreateInfoOutputFile() {
  51. const std::string &OutputFilename = getLibSupportInfoOutputFilename();
  52. if (OutputFilename.empty())
  53. return new raw_fd_ostream(2, false); // stderr.
  54. if (OutputFilename == "-")
  55. return new raw_fd_ostream(1, false); // stdout.
  56. // Append mode is used because the info output file is opened and closed
  57. // each time -stats or -time-passes wants to print output to it. To
  58. // compensate for this, the test-suite Makefiles have code to delete the
  59. // info output file before running commands which write to it.
  60. std::string Error;
  61. raw_ostream *Result = new raw_fd_ostream(OutputFilename.c_str(),
  62. Error, raw_fd_ostream::F_Append);
  63. if (Error.empty())
  64. return Result;
  65. errs() << "Error opening info-output-file '"
  66. << OutputFilename << " for appending!\n";
  67. delete Result;
  68. return new raw_fd_ostream(2, false); // stderr.
  69. }
  70. static TimerGroup *DefaultTimerGroup = 0;
  71. static TimerGroup *getDefaultTimerGroup() {
  72. TimerGroup *tmp = DefaultTimerGroup;
  73. sys::MemoryFence();
  74. if (tmp) return tmp;
  75. llvm_acquire_global_lock();
  76. tmp = DefaultTimerGroup;
  77. if (!tmp) {
  78. tmp = new TimerGroup("Miscellaneous Ungrouped Timers");
  79. sys::MemoryFence();
  80. DefaultTimerGroup = tmp;
  81. }
  82. llvm_release_global_lock();
  83. return tmp;
  84. }
  85. //===----------------------------------------------------------------------===//
  86. // Timer Implementation
  87. //===----------------------------------------------------------------------===//
  88. void Timer::init(StringRef N) {
  89. assert(TG == 0 && "Timer already initialized");
  90. Name.assign(N.begin(), N.end());
  91. Started = false;
  92. TG = getDefaultTimerGroup();
  93. TG->addTimer(*this);
  94. }
  95. void Timer::init(StringRef N, TimerGroup &tg) {
  96. assert(TG == 0 && "Timer already initialized");
  97. Name.assign(N.begin(), N.end());
  98. Started = false;
  99. TG = &tg;
  100. TG->addTimer(*this);
  101. }
  102. Timer::~Timer() {
  103. if (!TG) return; // Never initialized, or already cleared.
  104. TG->removeTimer(*this);
  105. }
  106. static inline size_t getMemUsage() {
  107. if (!TrackSpace) return 0;
  108. return sys::Process::GetMallocUsage();
  109. }
  110. TimeRecord TimeRecord::getCurrentTime(bool Start) {
  111. TimeRecord Result;
  112. sys::TimeValue now(0,0), user(0,0), sys(0,0);
  113. if (Start) {
  114. Result.MemUsed = getMemUsage();
  115. sys::Process::GetTimeUsage(now, user, sys);
  116. } else {
  117. sys::Process::GetTimeUsage(now, user, sys);
  118. Result.MemUsed = getMemUsage();
  119. }
  120. Result.WallTime = now.seconds() + now.microseconds() / 1000000.0;
  121. Result.UserTime = user.seconds() + user.microseconds() / 1000000.0;
  122. Result.SystemTime = sys.seconds() + sys.microseconds() / 1000000.0;
  123. return Result;
  124. }
  125. static ManagedStatic<std::vector<Timer*> > ActiveTimers;
  126. void Timer::startTimer() {
  127. Started = true;
  128. ActiveTimers->push_back(this);
  129. Time -= TimeRecord::getCurrentTime(true);
  130. }
  131. void Timer::stopTimer() {
  132. Time += TimeRecord::getCurrentTime(false);
  133. if (ActiveTimers->back() == this) {
  134. ActiveTimers->pop_back();
  135. } else {
  136. std::vector<Timer*>::iterator I =
  137. std::find(ActiveTimers->begin(), ActiveTimers->end(), this);
  138. assert(I != ActiveTimers->end() && "stop but no startTimer?");
  139. ActiveTimers->erase(I);
  140. }
  141. }
  142. static void printVal(double Val, double Total, raw_ostream &OS) {
  143. if (Total < 1e-7) // Avoid dividing by zero.
  144. OS << " ----- ";
  145. else
  146. OS << format(" %7.4f (%5.1f%%)", Val, Val*100/Total);
  147. }
  148. void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const {
  149. if (Total.getUserTime())
  150. printVal(getUserTime(), Total.getUserTime(), OS);
  151. if (Total.getSystemTime())
  152. printVal(getSystemTime(), Total.getSystemTime(), OS);
  153. if (Total.getProcessTime())
  154. printVal(getProcessTime(), Total.getProcessTime(), OS);
  155. printVal(getWallTime(), Total.getWallTime(), OS);
  156. OS << " ";
  157. if (Total.getMemUsed())
  158. OS << format("%9" PRId64 " ", (int64_t)getMemUsed());
  159. }
  160. //===----------------------------------------------------------------------===//
  161. // NamedRegionTimer Implementation
  162. //===----------------------------------------------------------------------===//
  163. namespace {
  164. typedef StringMap<Timer> Name2TimerMap;
  165. class Name2PairMap {
  166. StringMap<std::pair<TimerGroup*, Name2TimerMap> > Map;
  167. public:
  168. ~Name2PairMap() {
  169. for (StringMap<std::pair<TimerGroup*, Name2TimerMap> >::iterator
  170. I = Map.begin(), E = Map.end(); I != E; ++I)
  171. delete I->second.first;
  172. }
  173. Timer &get(StringRef Name, StringRef GroupName) {
  174. sys::SmartScopedLock<true> L(*TimerLock);
  175. std::pair<TimerGroup*, Name2TimerMap> &GroupEntry = Map[GroupName];
  176. if (!GroupEntry.first)
  177. GroupEntry.first = new TimerGroup(GroupName);
  178. Timer &T = GroupEntry.second[Name];
  179. if (!T.isInitialized())
  180. T.init(Name, *GroupEntry.first);
  181. return T;
  182. }
  183. };
  184. }
  185. static ManagedStatic<Name2TimerMap> NamedTimers;
  186. static ManagedStatic<Name2PairMap> NamedGroupedTimers;
  187. static Timer &getNamedRegionTimer(StringRef Name) {
  188. sys::SmartScopedLock<true> L(*TimerLock);
  189. Timer &T = (*NamedTimers)[Name];
  190. if (!T.isInitialized())
  191. T.init(Name);
  192. return T;
  193. }
  194. NamedRegionTimer::NamedRegionTimer(StringRef Name,
  195. bool Enabled)
  196. : TimeRegion(!Enabled ? 0 : &getNamedRegionTimer(Name)) {}
  197. NamedRegionTimer::NamedRegionTimer(StringRef Name, StringRef GroupName,
  198. bool Enabled)
  199. : TimeRegion(!Enabled ? 0 : &NamedGroupedTimers->get(Name, GroupName)) {}
  200. //===----------------------------------------------------------------------===//
  201. // TimerGroup Implementation
  202. //===----------------------------------------------------------------------===//
  203. /// TimerGroupList - This is the global list of TimerGroups, maintained by the
  204. /// TimerGroup ctor/dtor and is protected by the TimerLock lock.
  205. static TimerGroup *TimerGroupList = 0;
  206. TimerGroup::TimerGroup(StringRef name)
  207. : Name(name.begin(), name.end()), FirstTimer(0) {
  208. // Add the group to TimerGroupList.
  209. sys::SmartScopedLock<true> L(*TimerLock);
  210. if (TimerGroupList)
  211. TimerGroupList->Prev = &Next;
  212. Next = TimerGroupList;
  213. Prev = &TimerGroupList;
  214. TimerGroupList = this;
  215. }
  216. TimerGroup::~TimerGroup() {
  217. // If the timer group is destroyed before the timers it owns, accumulate and
  218. // print the timing data.
  219. while (FirstTimer != 0)
  220. removeTimer(*FirstTimer);
  221. // Remove the group from the TimerGroupList.
  222. sys::SmartScopedLock<true> L(*TimerLock);
  223. *Prev = Next;
  224. if (Next)
  225. Next->Prev = Prev;
  226. }
  227. void TimerGroup::removeTimer(Timer &T) {
  228. sys::SmartScopedLock<true> L(*TimerLock);
  229. // If the timer was started, move its data to TimersToPrint.
  230. if (T.Started)
  231. TimersToPrint.push_back(std::make_pair(T.Time, T.Name));
  232. T.TG = 0;
  233. // Unlink the timer from our list.
  234. *T.Prev = T.Next;
  235. if (T.Next)
  236. T.Next->Prev = T.Prev;
  237. // Print the report when all timers in this group are destroyed if some of
  238. // them were started.
  239. if (FirstTimer != 0 || TimersToPrint.empty())
  240. return;
  241. raw_ostream *OutStream = CreateInfoOutputFile();
  242. PrintQueuedTimers(*OutStream);
  243. delete OutStream; // Close the file.
  244. }
  245. void TimerGroup::addTimer(Timer &T) {
  246. sys::SmartScopedLock<true> L(*TimerLock);
  247. // Add the timer to our list.
  248. if (FirstTimer)
  249. FirstTimer->Prev = &T.Next;
  250. T.Next = FirstTimer;
  251. T.Prev = &FirstTimer;
  252. FirstTimer = &T;
  253. }
  254. void TimerGroup::PrintQueuedTimers(raw_ostream &OS) {
  255. // Sort the timers in descending order by amount of time taken.
  256. std::sort(TimersToPrint.begin(), TimersToPrint.end());
  257. TimeRecord Total;
  258. for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
  259. Total += TimersToPrint[i].first;
  260. // Print out timing header.
  261. OS << "===" << std::string(73, '-') << "===\n";
  262. // Figure out how many spaces to indent TimerGroup name.
  263. unsigned Padding = (80-Name.length())/2;
  264. if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
  265. OS.indent(Padding) << Name << '\n';
  266. OS << "===" << std::string(73, '-') << "===\n";
  267. // If this is not an collection of ungrouped times, print the total time.
  268. // Ungrouped timers don't really make sense to add up. We still print the
  269. // TOTAL line to make the percentages make sense.
  270. if (this != DefaultTimerGroup)
  271. OS << format(" Total Execution Time: %5.4f seconds (%5.4f wall clock)\n",
  272. Total.getProcessTime(), Total.getWallTime());
  273. OS << '\n';
  274. if (Total.getUserTime())
  275. OS << " ---User Time---";
  276. if (Total.getSystemTime())
  277. OS << " --System Time--";
  278. if (Total.getProcessTime())
  279. OS << " --User+System--";
  280. OS << " ---Wall Time---";
  281. if (Total.getMemUsed())
  282. OS << " ---Mem---";
  283. OS << " --- Name ---\n";
  284. // Loop through all of the timing data, printing it out.
  285. for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) {
  286. const std::pair<TimeRecord, std::string> &Entry = TimersToPrint[e-i-1];
  287. Entry.first.print(Total, OS);
  288. OS << Entry.second << '\n';
  289. }
  290. Total.print(Total, OS);
  291. OS << "Total\n\n";
  292. OS.flush();
  293. TimersToPrint.clear();
  294. }
  295. /// print - Print any started timers in this group and zero them.
  296. void TimerGroup::print(raw_ostream &OS) {
  297. sys::SmartScopedLock<true> L(*TimerLock);
  298. // See if any of our timers were started, if so add them to TimersToPrint and
  299. // reset them.
  300. for (Timer *T = FirstTimer; T; T = T->Next) {
  301. if (!T->Started) continue;
  302. TimersToPrint.push_back(std::make_pair(T->Time, T->Name));
  303. // Clear out the time.
  304. T->Started = 0;
  305. T->Time = TimeRecord();
  306. }
  307. // If any timers were started, print the group.
  308. if (!TimersToPrint.empty())
  309. PrintQueuedTimers(OS);
  310. }
  311. /// printAll - This static method prints all timers and clears them all out.
  312. void TimerGroup::printAll(raw_ostream &OS) {
  313. sys::SmartScopedLock<true> L(*TimerLock);
  314. for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
  315. TG->print(OS);
  316. }