Timer.cpp 11 KB

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