Timer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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/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. 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. std::unique_ptr<raw_fd_ostream> llvm::CreateInfoOutputFile() {
  49. const std::string &OutputFilename = getLibSupportInfoOutputFilename();
  50. if (OutputFilename.empty())
  51. return llvm::make_unique<raw_fd_ostream>(2, false); // stderr.
  52. if (OutputFilename == "-")
  53. return llvm::make_unique<raw_fd_ostream>(1, false); // stdout.
  54. // Append mode is used because the info output file is opened and closed
  55. // each time -stats or -time-passes wants to print output to it. To
  56. // compensate for this, the test-suite Makefiles have code to delete the
  57. // info output file before running commands which write to it.
  58. std::error_code EC;
  59. auto Result = llvm::make_unique<raw_fd_ostream>(
  60. OutputFilename, EC, sys::fs::F_Append | sys::fs::F_Text);
  61. if (!EC)
  62. return Result;
  63. errs() << "Error opening info-output-file '"
  64. << OutputFilename << " for appending!\n";
  65. return llvm::make_unique<raw_fd_ostream>(2, false); // stderr.
  66. }
  67. namespace {
  68. struct CreateDefaultTimerGroup {
  69. static void *call() {
  70. return new TimerGroup("misc", "Miscellaneous Ungrouped Timers");
  71. }
  72. };
  73. } // namespace
  74. static ManagedStatic<TimerGroup, CreateDefaultTimerGroup> DefaultTimerGroup;
  75. static TimerGroup *getDefaultTimerGroup() { return &*DefaultTimerGroup; }
  76. //===----------------------------------------------------------------------===//
  77. // Timer Implementation
  78. //===----------------------------------------------------------------------===//
  79. void Timer::init(StringRef Name, StringRef Description) {
  80. init(Name, Description, *getDefaultTimerGroup());
  81. }
  82. void Timer::init(StringRef Name, StringRef Description, TimerGroup &tg) {
  83. assert(!TG && "Timer already initialized");
  84. this->Name.assign(Name.begin(), Name.end());
  85. this->Description.assign(Description.begin(), Description.end());
  86. Running = Triggered = false;
  87. TG = &tg;
  88. TG->addTimer(*this);
  89. }
  90. Timer::~Timer() {
  91. if (!TG) return; // Never initialized, or already cleared.
  92. TG->removeTimer(*this);
  93. }
  94. static inline size_t getMemUsage() {
  95. if (!TrackSpace) return 0;
  96. return sys::Process::GetMallocUsage();
  97. }
  98. TimeRecord TimeRecord::getCurrentTime(bool Start) {
  99. using Seconds = std::chrono::duration<double, std::ratio<1>>;
  100. TimeRecord Result;
  101. sys::TimePoint<> now;
  102. std::chrono::nanoseconds user, sys;
  103. if (Start) {
  104. Result.MemUsed = getMemUsage();
  105. sys::Process::GetTimeUsage(now, user, sys);
  106. } else {
  107. sys::Process::GetTimeUsage(now, user, sys);
  108. Result.MemUsed = getMemUsage();
  109. }
  110. Result.WallTime = Seconds(now.time_since_epoch()).count();
  111. Result.UserTime = Seconds(user).count();
  112. Result.SystemTime = Seconds(sys).count();
  113. return Result;
  114. }
  115. void Timer::startTimer() {
  116. assert(!Running && "Cannot start a running timer");
  117. Running = Triggered = true;
  118. StartTime = TimeRecord::getCurrentTime(true);
  119. }
  120. void Timer::stopTimer() {
  121. assert(Running && "Cannot stop a paused timer");
  122. Running = false;
  123. Time += TimeRecord::getCurrentTime(false);
  124. Time -= StartTime;
  125. }
  126. void Timer::clear() {
  127. Running = Triggered = false;
  128. Time = StartTime = TimeRecord();
  129. }
  130. static void printVal(double Val, double Total, raw_ostream &OS) {
  131. if (Total < 1e-7) // Avoid dividing by zero.
  132. OS << " ----- ";
  133. else
  134. OS << format(" %7.4f (%5.1f%%)", Val, Val*100/Total);
  135. }
  136. void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const {
  137. if (Total.getUserTime())
  138. printVal(getUserTime(), Total.getUserTime(), OS);
  139. if (Total.getSystemTime())
  140. printVal(getSystemTime(), Total.getSystemTime(), OS);
  141. if (Total.getProcessTime())
  142. printVal(getProcessTime(), Total.getProcessTime(), OS);
  143. printVal(getWallTime(), Total.getWallTime(), OS);
  144. OS << " ";
  145. if (Total.getMemUsed())
  146. OS << format("%9" PRId64 " ", (int64_t)getMemUsed());
  147. }
  148. //===----------------------------------------------------------------------===//
  149. // NamedRegionTimer Implementation
  150. //===----------------------------------------------------------------------===//
  151. namespace {
  152. typedef StringMap<Timer> Name2TimerMap;
  153. class Name2PairMap {
  154. StringMap<std::pair<TimerGroup*, Name2TimerMap> > Map;
  155. public:
  156. ~Name2PairMap() {
  157. for (StringMap<std::pair<TimerGroup*, Name2TimerMap> >::iterator
  158. I = Map.begin(), E = Map.end(); I != E; ++I)
  159. delete I->second.first;
  160. }
  161. Timer &get(StringRef Name, StringRef Description, StringRef GroupName,
  162. StringRef GroupDescription) {
  163. sys::SmartScopedLock<true> L(*TimerLock);
  164. std::pair<TimerGroup*, Name2TimerMap> &GroupEntry = Map[GroupName];
  165. if (!GroupEntry.first)
  166. GroupEntry.first = new TimerGroup(GroupName, GroupDescription);
  167. Timer &T = GroupEntry.second[Name];
  168. if (!T.isInitialized())
  169. T.init(Name, Description, *GroupEntry.first);
  170. return T;
  171. }
  172. };
  173. }
  174. static ManagedStatic<Name2PairMap> NamedGroupedTimers;
  175. NamedRegionTimer::NamedRegionTimer(StringRef Name, StringRef Description,
  176. StringRef GroupName,
  177. StringRef GroupDescription, bool Enabled)
  178. : TimeRegion(!Enabled ? nullptr
  179. : &NamedGroupedTimers->get(Name, Description, GroupName,
  180. GroupDescription)) {}
  181. //===----------------------------------------------------------------------===//
  182. // TimerGroup Implementation
  183. //===----------------------------------------------------------------------===//
  184. /// This is the global list of TimerGroups, maintained by the TimerGroup
  185. /// ctor/dtor and is protected by the TimerLock lock.
  186. static TimerGroup *TimerGroupList = nullptr;
  187. TimerGroup::TimerGroup(StringRef Name, StringRef Description)
  188. : Name(Name.begin(), Name.end()),
  189. Description(Description.begin(), Description.end()) {
  190. // Add the group to TimerGroupList.
  191. sys::SmartScopedLock<true> L(*TimerLock);
  192. if (TimerGroupList)
  193. TimerGroupList->Prev = &Next;
  194. Next = TimerGroupList;
  195. Prev = &TimerGroupList;
  196. TimerGroupList = this;
  197. }
  198. TimerGroup::TimerGroup(StringRef Name, StringRef Description,
  199. const StringMap<TimeRecord> &Records)
  200. : TimerGroup(Name, Description) {
  201. TimersToPrint.reserve(Records.size());
  202. for (const auto &P : Records)
  203. TimersToPrint.emplace_back(P.getValue(), P.getKey(), P.getKey());
  204. assert(TimersToPrint.size() == Records.size() && "Size mismatch");
  205. }
  206. TimerGroup::~TimerGroup() {
  207. // If the timer group is destroyed before the timers it owns, accumulate and
  208. // print the timing data.
  209. while (FirstTimer)
  210. removeTimer(*FirstTimer);
  211. // Remove the group from the TimerGroupList.
  212. sys::SmartScopedLock<true> L(*TimerLock);
  213. *Prev = Next;
  214. if (Next)
  215. Next->Prev = Prev;
  216. }
  217. void TimerGroup::removeTimer(Timer &T) {
  218. sys::SmartScopedLock<true> L(*TimerLock);
  219. // If the timer was started, move its data to TimersToPrint.
  220. if (T.hasTriggered())
  221. TimersToPrint.emplace_back(T.Time, T.Name, T.Description);
  222. T.TG = nullptr;
  223. // Unlink the timer from our list.
  224. *T.Prev = T.Next;
  225. if (T.Next)
  226. T.Next->Prev = T.Prev;
  227. // Print the report when all timers in this group are destroyed if some of
  228. // them were started.
  229. if (FirstTimer || TimersToPrint.empty())
  230. return;
  231. std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
  232. PrintQueuedTimers(*OutStream);
  233. }
  234. void TimerGroup::addTimer(Timer &T) {
  235. sys::SmartScopedLock<true> L(*TimerLock);
  236. // Add the timer to our list.
  237. if (FirstTimer)
  238. FirstTimer->Prev = &T.Next;
  239. T.Next = FirstTimer;
  240. T.Prev = &FirstTimer;
  241. FirstTimer = &T;
  242. }
  243. void TimerGroup::PrintQueuedTimers(raw_ostream &OS) {
  244. // Sort the timers in descending order by amount of time taken.
  245. llvm::sort(TimersToPrint.begin(), TimersToPrint.end());
  246. TimeRecord Total;
  247. for (const PrintRecord &Record : TimersToPrint)
  248. Total += Record.Time;
  249. // Print out timing header.
  250. OS << "===" << std::string(73, '-') << "===\n";
  251. // Figure out how many spaces to indent TimerGroup name.
  252. unsigned Padding = (80-Description.length())/2;
  253. if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
  254. OS.indent(Padding) << Description << '\n';
  255. OS << "===" << std::string(73, '-') << "===\n";
  256. // If this is not an collection of ungrouped times, print the total time.
  257. // Ungrouped timers don't really make sense to add up. We still print the
  258. // TOTAL line to make the percentages make sense.
  259. if (this != getDefaultTimerGroup())
  260. OS << format(" Total Execution Time: %5.4f seconds (%5.4f wall clock)\n",
  261. Total.getProcessTime(), Total.getWallTime());
  262. OS << '\n';
  263. if (Total.getUserTime())
  264. OS << " ---User Time---";
  265. if (Total.getSystemTime())
  266. OS << " --System Time--";
  267. if (Total.getProcessTime())
  268. OS << " --User+System--";
  269. OS << " ---Wall Time---";
  270. if (Total.getMemUsed())
  271. OS << " ---Mem---";
  272. OS << " --- Name ---\n";
  273. // Loop through all of the timing data, printing it out.
  274. for (const PrintRecord &Record : make_range(TimersToPrint.rbegin(),
  275. TimersToPrint.rend())) {
  276. Record.Time.print(Total, OS);
  277. OS << Record.Description << '\n';
  278. }
  279. Total.print(Total, OS);
  280. OS << "Total\n\n";
  281. OS.flush();
  282. TimersToPrint.clear();
  283. }
  284. void TimerGroup::prepareToPrintList() {
  285. // See if any of our timers were started, if so add them to TimersToPrint.
  286. for (Timer *T = FirstTimer; T; T = T->Next) {
  287. if (!T->hasTriggered()) continue;
  288. bool WasRunning = T->isRunning();
  289. if (WasRunning)
  290. T->stopTimer();
  291. TimersToPrint.emplace_back(T->Time, T->Name, T->Description);
  292. if (WasRunning)
  293. T->startTimer();
  294. }
  295. }
  296. void TimerGroup::print(raw_ostream &OS) {
  297. sys::SmartScopedLock<true> L(*TimerLock);
  298. prepareToPrintList();
  299. // If any timers were started, print the group.
  300. if (!TimersToPrint.empty())
  301. PrintQueuedTimers(OS);
  302. }
  303. void TimerGroup::clear() {
  304. sys::SmartScopedLock<true> L(*TimerLock);
  305. for (Timer *T = FirstTimer; T; T = T->Next)
  306. T->clear();
  307. }
  308. void TimerGroup::printAll(raw_ostream &OS) {
  309. sys::SmartScopedLock<true> L(*TimerLock);
  310. for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
  311. TG->print(OS);
  312. }
  313. void TimerGroup::clearAll() {
  314. sys::SmartScopedLock<true> L(*TimerLock);
  315. for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
  316. TG->clear();
  317. }
  318. void TimerGroup::printJSONValue(raw_ostream &OS, const PrintRecord &R,
  319. const char *suffix, double Value) {
  320. assert(yaml::needsQuotes(Name) == yaml::QuotingType::None &&
  321. "TimerGroup name should not need quotes");
  322. assert(yaml::needsQuotes(R.Name) == yaml::QuotingType::None &&
  323. "Timer name should not need quotes");
  324. constexpr auto max_digits10 = std::numeric_limits<double>::max_digits10;
  325. OS << "\t\"time." << Name << '.' << R.Name << suffix
  326. << "\": " << format("%.*e", max_digits10 - 1, Value);
  327. }
  328. const char *TimerGroup::printJSONValues(raw_ostream &OS, const char *delim) {
  329. sys::SmartScopedLock<true> L(*TimerLock);
  330. prepareToPrintList();
  331. for (const PrintRecord &R : TimersToPrint) {
  332. OS << delim;
  333. delim = ",\n";
  334. const TimeRecord &T = R.Time;
  335. printJSONValue(OS, R, ".wall", T.getWallTime());
  336. OS << delim;
  337. printJSONValue(OS, R, ".user", T.getUserTime());
  338. OS << delim;
  339. printJSONValue(OS, R, ".sys", T.getSystemTime());
  340. if (T.getMemUsed()) {
  341. OS << delim;
  342. printJSONValue(OS, R, ".mem", T.getMemUsed());
  343. }
  344. }
  345. TimersToPrint.clear();
  346. return delim;
  347. }
  348. const char *TimerGroup::printAllJSONValues(raw_ostream &OS, const char *delim) {
  349. sys::SmartScopedLock<true> L(*TimerLock);
  350. for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
  351. delim = TG->printJSONValues(OS, delim);
  352. return delim;
  353. }
  354. void TimerGroup::ConstructTimerLists() {
  355. (void)*NamedGroupedTimers;
  356. }