Timer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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("misc", "Miscellaneous Ungrouped Timers");
  74. sys::MemoryFence();
  75. DefaultTimerGroup = tmp;
  76. }
  77. return tmp;
  78. }
  79. //===----------------------------------------------------------------------===//
  80. // Timer Implementation
  81. //===----------------------------------------------------------------------===//
  82. void Timer::init(StringRef Name, StringRef Description) {
  83. init(Name, Description, *getDefaultTimerGroup());
  84. }
  85. void Timer::init(StringRef Name, StringRef Description, TimerGroup &tg) {
  86. assert(!TG && "Timer already initialized");
  87. this->Name.assign(Name.begin(), Name.end());
  88. this->Description.assign(Description.begin(), Description.end());
  89. Running = Triggered = false;
  90. TG = &tg;
  91. TG->addTimer(*this);
  92. }
  93. Timer::~Timer() {
  94. if (!TG) return; // Never initialized, or already cleared.
  95. TG->removeTimer(*this);
  96. }
  97. static inline size_t getMemUsage() {
  98. if (!TrackSpace) return 0;
  99. return sys::Process::GetMallocUsage();
  100. }
  101. TimeRecord TimeRecord::getCurrentTime(bool Start) {
  102. using Seconds = std::chrono::duration<double, std::ratio<1>>;
  103. TimeRecord Result;
  104. sys::TimePoint<> now;
  105. std::chrono::nanoseconds user, sys;
  106. if (Start) {
  107. Result.MemUsed = getMemUsage();
  108. sys::Process::GetTimeUsage(now, user, sys);
  109. } else {
  110. sys::Process::GetTimeUsage(now, user, sys);
  111. Result.MemUsed = getMemUsage();
  112. }
  113. Result.WallTime = Seconds(now.time_since_epoch()).count();
  114. Result.UserTime = Seconds(user).count();
  115. Result.SystemTime = Seconds(sys).count();
  116. return Result;
  117. }
  118. void Timer::startTimer() {
  119. assert(!Running && "Cannot start a running timer");
  120. Running = Triggered = true;
  121. StartTime = TimeRecord::getCurrentTime(true);
  122. }
  123. void Timer::stopTimer() {
  124. assert(Running && "Cannot stop a paused timer");
  125. Running = false;
  126. Time += TimeRecord::getCurrentTime(false);
  127. Time -= StartTime;
  128. }
  129. void Timer::clear() {
  130. Running = Triggered = false;
  131. Time = StartTime = TimeRecord();
  132. }
  133. static void printVal(double Val, double Total, raw_ostream &OS) {
  134. if (Total < 1e-7) // Avoid dividing by zero.
  135. OS << " ----- ";
  136. else
  137. OS << format(" %7.4f (%5.1f%%)", Val, Val*100/Total);
  138. }
  139. void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const {
  140. if (Total.getUserTime())
  141. printVal(getUserTime(), Total.getUserTime(), OS);
  142. if (Total.getSystemTime())
  143. printVal(getSystemTime(), Total.getSystemTime(), OS);
  144. if (Total.getProcessTime())
  145. printVal(getProcessTime(), Total.getProcessTime(), OS);
  146. printVal(getWallTime(), Total.getWallTime(), OS);
  147. OS << " ";
  148. if (Total.getMemUsed())
  149. OS << format("%9" PRId64 " ", (int64_t)getMemUsed());
  150. }
  151. //===----------------------------------------------------------------------===//
  152. // NamedRegionTimer Implementation
  153. //===----------------------------------------------------------------------===//
  154. namespace {
  155. typedef StringMap<Timer> Name2TimerMap;
  156. class Name2PairMap {
  157. StringMap<std::pair<TimerGroup*, Name2TimerMap> > Map;
  158. public:
  159. ~Name2PairMap() {
  160. for (StringMap<std::pair<TimerGroup*, Name2TimerMap> >::iterator
  161. I = Map.begin(), E = Map.end(); I != E; ++I)
  162. delete I->second.first;
  163. }
  164. Timer &get(StringRef Name, StringRef Description, StringRef GroupName,
  165. StringRef GroupDescription) {
  166. sys::SmartScopedLock<true> L(*TimerLock);
  167. std::pair<TimerGroup*, Name2TimerMap> &GroupEntry = Map[GroupName];
  168. if (!GroupEntry.first)
  169. GroupEntry.first = new TimerGroup(GroupName, GroupDescription);
  170. Timer &T = GroupEntry.second[Name];
  171. if (!T.isInitialized())
  172. T.init(Name, Description, *GroupEntry.first);
  173. return T;
  174. }
  175. };
  176. }
  177. static ManagedStatic<Name2PairMap> NamedGroupedTimers;
  178. NamedRegionTimer::NamedRegionTimer(StringRef Name, StringRef Description,
  179. StringRef GroupName,
  180. StringRef GroupDescription, bool Enabled)
  181. : TimeRegion(!Enabled ? nullptr
  182. : &NamedGroupedTimers->get(Name, Description, GroupName,
  183. GroupDescription)) {}
  184. //===----------------------------------------------------------------------===//
  185. // TimerGroup Implementation
  186. //===----------------------------------------------------------------------===//
  187. /// This is the global list of TimerGroups, maintained by the TimerGroup
  188. /// ctor/dtor and is protected by the TimerLock lock.
  189. static TimerGroup *TimerGroupList = nullptr;
  190. TimerGroup::TimerGroup(StringRef Name, StringRef Description)
  191. : Name(Name.begin(), Name.end()),
  192. Description(Description.begin(), Description.end()) {
  193. // Add the group to TimerGroupList.
  194. sys::SmartScopedLock<true> L(*TimerLock);
  195. if (TimerGroupList)
  196. TimerGroupList->Prev = &Next;
  197. Next = TimerGroupList;
  198. Prev = &TimerGroupList;
  199. TimerGroupList = this;
  200. }
  201. TimerGroup::~TimerGroup() {
  202. // If the timer group is destroyed before the timers it owns, accumulate and
  203. // print the timing data.
  204. while (FirstTimer)
  205. removeTimer(*FirstTimer);
  206. // Remove the group from the TimerGroupList.
  207. sys::SmartScopedLock<true> L(*TimerLock);
  208. *Prev = Next;
  209. if (Next)
  210. Next->Prev = Prev;
  211. }
  212. void TimerGroup::removeTimer(Timer &T) {
  213. sys::SmartScopedLock<true> L(*TimerLock);
  214. // If the timer was started, move its data to TimersToPrint.
  215. if (T.hasTriggered())
  216. TimersToPrint.emplace_back(T.Time, T.Description);
  217. T.TG = nullptr;
  218. // Unlink the timer from our list.
  219. *T.Prev = T.Next;
  220. if (T.Next)
  221. T.Next->Prev = T.Prev;
  222. // Print the report when all timers in this group are destroyed if some of
  223. // them were started.
  224. if (FirstTimer || TimersToPrint.empty())
  225. return;
  226. std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
  227. PrintQueuedTimers(*OutStream);
  228. }
  229. void TimerGroup::addTimer(Timer &T) {
  230. sys::SmartScopedLock<true> L(*TimerLock);
  231. // Add the timer to our list.
  232. if (FirstTimer)
  233. FirstTimer->Prev = &T.Next;
  234. T.Next = FirstTimer;
  235. T.Prev = &FirstTimer;
  236. FirstTimer = &T;
  237. }
  238. void TimerGroup::PrintQueuedTimers(raw_ostream &OS) {
  239. // Sort the timers in descending order by amount of time taken.
  240. std::sort(TimersToPrint.begin(), TimersToPrint.end());
  241. TimeRecord Total;
  242. for (auto &RecordNamePair : TimersToPrint)
  243. Total += RecordNamePair.first;
  244. // Print out timing header.
  245. OS << "===" << std::string(73, '-') << "===\n";
  246. // Figure out how many spaces to indent TimerGroup name.
  247. unsigned Padding = (80-Description.length())/2;
  248. if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
  249. OS.indent(Padding) << Description << '\n';
  250. OS << "===" << std::string(73, '-') << "===\n";
  251. // If this is not an collection of ungrouped times, print the total time.
  252. // Ungrouped timers don't really make sense to add up. We still print the
  253. // TOTAL line to make the percentages make sense.
  254. if (this != DefaultTimerGroup)
  255. OS << format(" Total Execution Time: %5.4f seconds (%5.4f wall clock)\n",
  256. Total.getProcessTime(), Total.getWallTime());
  257. OS << '\n';
  258. if (Total.getUserTime())
  259. OS << " ---User Time---";
  260. if (Total.getSystemTime())
  261. OS << " --System Time--";
  262. if (Total.getProcessTime())
  263. OS << " --User+System--";
  264. OS << " ---Wall Time---";
  265. if (Total.getMemUsed())
  266. OS << " ---Mem---";
  267. OS << " --- Name ---\n";
  268. // Loop through all of the timing data, printing it out.
  269. for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) {
  270. const std::pair<TimeRecord, std::string> &Entry = TimersToPrint[e-i-1];
  271. Entry.first.print(Total, OS);
  272. OS << Entry.second << '\n';
  273. }
  274. Total.print(Total, OS);
  275. OS << "Total\n\n";
  276. OS.flush();
  277. TimersToPrint.clear();
  278. }
  279. void TimerGroup::print(raw_ostream &OS) {
  280. sys::SmartScopedLock<true> L(*TimerLock);
  281. // See if any of our timers were started, if so add them to TimersToPrint and
  282. // reset them.
  283. for (Timer *T = FirstTimer; T; T = T->Next) {
  284. if (!T->hasTriggered()) continue;
  285. TimersToPrint.emplace_back(T->Time, T->Description);
  286. // Clear out the time.
  287. T->clear();
  288. }
  289. // If any timers were started, print the group.
  290. if (!TimersToPrint.empty())
  291. PrintQueuedTimers(OS);
  292. }
  293. void TimerGroup::printAll(raw_ostream &OS) {
  294. sys::SmartScopedLock<true> L(*TimerLock);
  295. for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
  296. TG->print(OS);
  297. }