Timer.cpp 12 KB

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