Timer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. //===-- Timer.cpp - Interval Timing Support -------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. /// \file Interval Timing implementation.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Support/Timer.h"
  13. #include "llvm/ADT/Statistic.h"
  14. #include "llvm/ADT/StringMap.h"
  15. #include "llvm/Support/CommandLine.h"
  16. #include "llvm/Support/FileSystem.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/Signposts.h"
  22. #include "llvm/Support/YAMLTraits.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include <limits>
  25. using namespace llvm;
  26. // This ugly hack is brought to you courtesy of constructor/destructor ordering
  27. // being unspecified by C++. Basically the problem is that a Statistic object
  28. // gets destroyed, which ends up calling 'GetLibSupportInfoOutputFile()'
  29. // (below), which calls this function. LibSupportInfoOutputFilename used to be
  30. // a global variable, but sometimes it would get destroyed before the Statistic,
  31. // causing havoc to ensue. We "fix" this by creating the string the first time
  32. // it is needed and never destroying it.
  33. static ManagedStatic<std::string> LibSupportInfoOutputFilename;
  34. static std::string &getLibSupportInfoOutputFilename() {
  35. return *LibSupportInfoOutputFilename;
  36. }
  37. static ManagedStatic<sys::SmartMutex<true> > TimerLock;
  38. /// Allows llvm::Timer to emit signposts when supported.
  39. static ManagedStatic<SignpostEmitter> Signposts;
  40. namespace {
  41. static cl::opt<bool>
  42. TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
  43. "tracking (this may be slow)"),
  44. cl::Hidden);
  45. static cl::opt<std::string, true>
  46. InfoOutputFilename("info-output-file", cl::value_desc("filename"),
  47. cl::desc("File to append -stats and -timer output to"),
  48. cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
  49. }
  50. std::unique_ptr<raw_fd_ostream> llvm::CreateInfoOutputFile() {
  51. const std::string &OutputFilename = getLibSupportInfoOutputFilename();
  52. if (OutputFilename.empty())
  53. return llvm::make_unique<raw_fd_ostream>(2, false); // stderr.
  54. if (OutputFilename == "-")
  55. return llvm::make_unique<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::error_code EC;
  61. auto Result = llvm::make_unique<raw_fd_ostream>(
  62. OutputFilename, EC, sys::fs::OF_Append | sys::fs::OF_Text);
  63. if (!EC)
  64. return Result;
  65. errs() << "Error opening info-output-file '"
  66. << OutputFilename << " for appending!\n";
  67. return llvm::make_unique<raw_fd_ostream>(2, false); // stderr.
  68. }
  69. namespace {
  70. struct CreateDefaultTimerGroup {
  71. static void *call() {
  72. return new TimerGroup("misc", "Miscellaneous Ungrouped Timers");
  73. }
  74. };
  75. } // namespace
  76. static ManagedStatic<TimerGroup, CreateDefaultTimerGroup> DefaultTimerGroup;
  77. static TimerGroup *getDefaultTimerGroup() { return &*DefaultTimerGroup; }
  78. //===----------------------------------------------------------------------===//
  79. // Timer Implementation
  80. //===----------------------------------------------------------------------===//
  81. void Timer::init(StringRef Name, StringRef Description) {
  82. init(Name, Description, *getDefaultTimerGroup());
  83. }
  84. void Timer::init(StringRef Name, StringRef Description, TimerGroup &tg) {
  85. assert(!TG && "Timer already initialized");
  86. this->Name.assign(Name.begin(), Name.end());
  87. this->Description.assign(Description.begin(), Description.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. Signposts->startTimerInterval(this);
  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. Signposts->endTimerInterval(this);
  129. }
  130. void Timer::clear() {
  131. Running = Triggered = false;
  132. Time = StartTime = TimeRecord();
  133. }
  134. static void printVal(double Val, double Total, raw_ostream &OS) {
  135. if (Total < 1e-7) // Avoid dividing by zero.
  136. OS << " ----- ";
  137. else
  138. OS << format(" %7.4f (%5.1f%%)", Val, Val*100/Total);
  139. }
  140. void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const {
  141. if (Total.getUserTime())
  142. printVal(getUserTime(), Total.getUserTime(), OS);
  143. if (Total.getSystemTime())
  144. printVal(getSystemTime(), Total.getSystemTime(), OS);
  145. if (Total.getProcessTime())
  146. printVal(getProcessTime(), Total.getProcessTime(), OS);
  147. printVal(getWallTime(), Total.getWallTime(), OS);
  148. OS << " ";
  149. if (Total.getMemUsed())
  150. OS << format("%9" PRId64 " ", (int64_t)getMemUsed());
  151. }
  152. //===----------------------------------------------------------------------===//
  153. // NamedRegionTimer Implementation
  154. //===----------------------------------------------------------------------===//
  155. namespace {
  156. typedef StringMap<Timer> Name2TimerMap;
  157. class Name2PairMap {
  158. StringMap<std::pair<TimerGroup*, Name2TimerMap> > Map;
  159. public:
  160. ~Name2PairMap() {
  161. for (StringMap<std::pair<TimerGroup*, Name2TimerMap> >::iterator
  162. I = Map.begin(), E = Map.end(); I != E; ++I)
  163. delete I->second.first;
  164. }
  165. Timer &get(StringRef Name, StringRef Description, StringRef GroupName,
  166. StringRef GroupDescription) {
  167. sys::SmartScopedLock<true> L(*TimerLock);
  168. std::pair<TimerGroup*, Name2TimerMap> &GroupEntry = Map[GroupName];
  169. if (!GroupEntry.first)
  170. GroupEntry.first = new TimerGroup(GroupName, GroupDescription);
  171. Timer &T = GroupEntry.second[Name];
  172. if (!T.isInitialized())
  173. T.init(Name, Description, *GroupEntry.first);
  174. return T;
  175. }
  176. };
  177. }
  178. static ManagedStatic<Name2PairMap> NamedGroupedTimers;
  179. NamedRegionTimer::NamedRegionTimer(StringRef Name, StringRef Description,
  180. StringRef GroupName,
  181. StringRef GroupDescription, bool Enabled)
  182. : TimeRegion(!Enabled ? nullptr
  183. : &NamedGroupedTimers->get(Name, Description, GroupName,
  184. GroupDescription)) {}
  185. //===----------------------------------------------------------------------===//
  186. // TimerGroup Implementation
  187. //===----------------------------------------------------------------------===//
  188. /// This is the global list of TimerGroups, maintained by the TimerGroup
  189. /// ctor/dtor and is protected by the TimerLock lock.
  190. static TimerGroup *TimerGroupList = nullptr;
  191. TimerGroup::TimerGroup(StringRef Name, StringRef Description)
  192. : Name(Name.begin(), Name.end()),
  193. Description(Description.begin(), Description.end()) {
  194. // Add the group to TimerGroupList.
  195. sys::SmartScopedLock<true> L(*TimerLock);
  196. if (TimerGroupList)
  197. TimerGroupList->Prev = &Next;
  198. Next = TimerGroupList;
  199. Prev = &TimerGroupList;
  200. TimerGroupList = this;
  201. }
  202. TimerGroup::TimerGroup(StringRef Name, StringRef Description,
  203. const StringMap<TimeRecord> &Records)
  204. : TimerGroup(Name, Description) {
  205. TimersToPrint.reserve(Records.size());
  206. for (const auto &P : Records)
  207. TimersToPrint.emplace_back(P.getValue(), P.getKey(), P.getKey());
  208. assert(TimersToPrint.size() == Records.size() && "Size mismatch");
  209. }
  210. TimerGroup::~TimerGroup() {
  211. // If the timer group is destroyed before the timers it owns, accumulate and
  212. // print the timing data.
  213. while (FirstTimer)
  214. removeTimer(*FirstTimer);
  215. // Remove the group from the TimerGroupList.
  216. sys::SmartScopedLock<true> L(*TimerLock);
  217. *Prev = Next;
  218. if (Next)
  219. Next->Prev = Prev;
  220. }
  221. void TimerGroup::removeTimer(Timer &T) {
  222. sys::SmartScopedLock<true> L(*TimerLock);
  223. // If the timer was started, move its data to TimersToPrint.
  224. if (T.hasTriggered())
  225. TimersToPrint.emplace_back(T.Time, T.Name, T.Description);
  226. T.TG = nullptr;
  227. // Unlink the timer from our list.
  228. *T.Prev = T.Next;
  229. if (T.Next)
  230. T.Next->Prev = T.Prev;
  231. // Print the report when all timers in this group are destroyed if some of
  232. // them were started.
  233. if (FirstTimer || TimersToPrint.empty())
  234. return;
  235. std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
  236. PrintQueuedTimers(*OutStream);
  237. }
  238. void TimerGroup::addTimer(Timer &T) {
  239. sys::SmartScopedLock<true> L(*TimerLock);
  240. // Add the timer to our list.
  241. if (FirstTimer)
  242. FirstTimer->Prev = &T.Next;
  243. T.Next = FirstTimer;
  244. T.Prev = &FirstTimer;
  245. FirstTimer = &T;
  246. }
  247. void TimerGroup::PrintQueuedTimers(raw_ostream &OS) {
  248. // Sort the timers in descending order by amount of time taken.
  249. llvm::sort(TimersToPrint);
  250. TimeRecord Total;
  251. for (const PrintRecord &Record : TimersToPrint)
  252. Total += Record.Time;
  253. // Print out timing header.
  254. OS << "===" << std::string(73, '-') << "===\n";
  255. // Figure out how many spaces to indent TimerGroup name.
  256. unsigned Padding = (80-Description.length())/2;
  257. if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
  258. OS.indent(Padding) << Description << '\n';
  259. OS << "===" << std::string(73, '-') << "===\n";
  260. // If this is not an collection of ungrouped times, print the total time.
  261. // Ungrouped timers don't really make sense to add up. We still print the
  262. // TOTAL line to make the percentages make sense.
  263. if (this != getDefaultTimerGroup())
  264. OS << format(" Total Execution Time: %5.4f seconds (%5.4f wall clock)\n",
  265. Total.getProcessTime(), Total.getWallTime());
  266. OS << '\n';
  267. if (Total.getUserTime())
  268. OS << " ---User Time---";
  269. if (Total.getSystemTime())
  270. OS << " --System Time--";
  271. if (Total.getProcessTime())
  272. OS << " --User+System--";
  273. OS << " ---Wall Time---";
  274. if (Total.getMemUsed())
  275. OS << " ---Mem---";
  276. OS << " --- Name ---\n";
  277. // Loop through all of the timing data, printing it out.
  278. for (const PrintRecord &Record : make_range(TimersToPrint.rbegin(),
  279. TimersToPrint.rend())) {
  280. Record.Time.print(Total, OS);
  281. OS << Record.Description << '\n';
  282. }
  283. Total.print(Total, OS);
  284. OS << "Total\n\n";
  285. OS.flush();
  286. TimersToPrint.clear();
  287. }
  288. void TimerGroup::prepareToPrintList(bool ResetTime) {
  289. // See if any of our timers were started, if so add them to TimersToPrint.
  290. for (Timer *T = FirstTimer; T; T = T->Next) {
  291. if (!T->hasTriggered()) continue;
  292. bool WasRunning = T->isRunning();
  293. if (WasRunning)
  294. T->stopTimer();
  295. TimersToPrint.emplace_back(T->Time, T->Name, T->Description);
  296. if (ResetTime)
  297. T->clear();
  298. if (WasRunning)
  299. T->startTimer();
  300. }
  301. }
  302. void TimerGroup::print(raw_ostream &OS, bool ResetAfterPrint) {
  303. {
  304. // After preparing the timers we can free the lock
  305. sys::SmartScopedLock<true> L(*TimerLock);
  306. prepareToPrintList(ResetAfterPrint);
  307. }
  308. // If any timers were started, print the group.
  309. if (!TimersToPrint.empty())
  310. PrintQueuedTimers(OS);
  311. }
  312. void TimerGroup::clear() {
  313. sys::SmartScopedLock<true> L(*TimerLock);
  314. for (Timer *T = FirstTimer; T; T = T->Next)
  315. T->clear();
  316. }
  317. void TimerGroup::printAll(raw_ostream &OS) {
  318. sys::SmartScopedLock<true> L(*TimerLock);
  319. for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
  320. TG->print(OS);
  321. }
  322. void TimerGroup::clearAll() {
  323. sys::SmartScopedLock<true> L(*TimerLock);
  324. for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
  325. TG->clear();
  326. }
  327. void TimerGroup::printJSONValue(raw_ostream &OS, const PrintRecord &R,
  328. const char *suffix, double Value) {
  329. assert(yaml::needsQuotes(Name) == yaml::QuotingType::None &&
  330. "TimerGroup name should not need quotes");
  331. assert(yaml::needsQuotes(R.Name) == yaml::QuotingType::None &&
  332. "Timer name should not need quotes");
  333. constexpr auto max_digits10 = std::numeric_limits<double>::max_digits10;
  334. OS << "\t\"time." << Name << '.' << R.Name << suffix
  335. << "\": " << format("%.*e", max_digits10 - 1, Value);
  336. }
  337. const char *TimerGroup::printJSONValues(raw_ostream &OS, const char *delim) {
  338. sys::SmartScopedLock<true> L(*TimerLock);
  339. prepareToPrintList(false);
  340. for (const PrintRecord &R : TimersToPrint) {
  341. OS << delim;
  342. delim = ",\n";
  343. const TimeRecord &T = R.Time;
  344. printJSONValue(OS, R, ".wall", T.getWallTime());
  345. OS << delim;
  346. printJSONValue(OS, R, ".user", T.getUserTime());
  347. OS << delim;
  348. printJSONValue(OS, R, ".sys", T.getSystemTime());
  349. if (T.getMemUsed()) {
  350. OS << delim;
  351. printJSONValue(OS, R, ".mem", T.getMemUsed());
  352. }
  353. }
  354. TimersToPrint.clear();
  355. return delim;
  356. }
  357. const char *TimerGroup::printAllJSONValues(raw_ostream &OS, const char *delim) {
  358. sys::SmartScopedLock<true> L(*TimerLock);
  359. for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
  360. delim = TG->printJSONValues(OS, delim);
  361. return delim;
  362. }
  363. void TimerGroup::ConstructTimerLists() {
  364. (void)*NamedGroupedTimers;
  365. }