Timer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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/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. // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
  25. // of constructor/destructor ordering being unspecified by C++. Basically the
  26. // problem is that a Statistic object gets destroyed, which ends up calling
  27. // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
  28. // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
  29. // would get destroyed before the Statistic, causing havoc to ensue. We "fix"
  30. // this by creating the string the first time it is needed and never destroying
  31. // it.
  32. static ManagedStatic<std::string> LibSupportInfoOutputFilename;
  33. static std::string &getLibSupportInfoOutputFilename() {
  34. return *LibSupportInfoOutputFilename;
  35. }
  36. static ManagedStatic<sys::SmartMutex<true> > TimerLock;
  37. namespace {
  38. static cl::opt<bool>
  39. TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
  40. "tracking (this may be slow)"),
  41. cl::Hidden);
  42. static cl::opt<std::string, true>
  43. InfoOutputFilename("info-output-file", cl::value_desc("filename"),
  44. cl::desc("File to append -stats and -timer output to"),
  45. cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
  46. }
  47. // Return a file stream to print our output on.
  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. static TimerGroup *DefaultTimerGroup = nullptr;
  68. static TimerGroup *getDefaultTimerGroup() {
  69. TimerGroup *tmp = DefaultTimerGroup;
  70. sys::MemoryFence();
  71. if (tmp) return tmp;
  72. sys::SmartScopedLock<true> Lock(*TimerLock);
  73. tmp = DefaultTimerGroup;
  74. if (!tmp) {
  75. tmp = new TimerGroup("Miscellaneous Ungrouped Timers");
  76. sys::MemoryFence();
  77. DefaultTimerGroup = tmp;
  78. }
  79. return tmp;
  80. }
  81. //===----------------------------------------------------------------------===//
  82. // Timer Implementation
  83. //===----------------------------------------------------------------------===//
  84. void Timer::init(StringRef N) {
  85. init(N, *getDefaultTimerGroup());
  86. }
  87. void Timer::init(StringRef N, TimerGroup &tg) {
  88. assert(!TG && "Timer already initialized");
  89. Name.assign(N.begin(), N.end());
  90. Running = Triggered = false;
  91. TG = &tg;
  92. TG->addTimer(*this);
  93. }
  94. Timer::~Timer() {
  95. if (!TG) return; // Never initialized, or already cleared.
  96. TG->removeTimer(*this);
  97. }
  98. static inline size_t getMemUsage() {
  99. if (!TrackSpace) return 0;
  100. return sys::Process::GetMallocUsage();
  101. }
  102. TimeRecord TimeRecord::getCurrentTime(bool Start) {
  103. TimeRecord Result;
  104. sys::TimeValue now(0,0), user(0,0), sys(0,0);
  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 = now.seconds() + now.microseconds() / 1000000.0;
  113. Result.UserTime = user.seconds() + user.microseconds() / 1000000.0;
  114. Result.SystemTime = sys.seconds() + sys.microseconds() / 1000000.0;
  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<Name2TimerMap> NamedTimers;
  176. static ManagedStatic<Name2PairMap> NamedGroupedTimers;
  177. static Timer &getNamedRegionTimer(StringRef Name) {
  178. sys::SmartScopedLock<true> L(*TimerLock);
  179. Timer &T = (*NamedTimers)[Name];
  180. if (!T.isInitialized())
  181. T.init(Name);
  182. return T;
  183. }
  184. NamedRegionTimer::NamedRegionTimer(StringRef Name,
  185. bool Enabled)
  186. : TimeRegion(!Enabled ? nullptr : &getNamedRegionTimer(Name)) {}
  187. NamedRegionTimer::NamedRegionTimer(StringRef Name, StringRef GroupName,
  188. bool Enabled)
  189. : TimeRegion(!Enabled ? nullptr : &NamedGroupedTimers->get(Name, GroupName)){}
  190. //===----------------------------------------------------------------------===//
  191. // TimerGroup Implementation
  192. //===----------------------------------------------------------------------===//
  193. /// TimerGroupList - This is the global list of TimerGroups, maintained by the
  194. /// TimerGroup ctor/dtor and is protected by the TimerLock lock.
  195. static TimerGroup *TimerGroupList = nullptr;
  196. TimerGroup::TimerGroup(StringRef name)
  197. : Name(name.begin(), name.end()), FirstTimer(nullptr) {
  198. // Add the group to TimerGroupList.
  199. sys::SmartScopedLock<true> L(*TimerLock);
  200. if (TimerGroupList)
  201. TimerGroupList->Prev = &Next;
  202. Next = TimerGroupList;
  203. Prev = &TimerGroupList;
  204. TimerGroupList = this;
  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);
  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. std::sort(TimersToPrint.begin(), TimersToPrint.end());
  246. TimeRecord Total;
  247. for (auto &RecordNamePair : TimersToPrint)
  248. Total += RecordNamePair.first;
  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-Name.length())/2;
  253. if (Padding > 80) Padding = 0; // Don't allow "negative" numbers
  254. OS.indent(Padding) << Name << '\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 != DefaultTimerGroup)
  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 (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) {
  275. const std::pair<TimeRecord, std::string> &Entry = TimersToPrint[e-i-1];
  276. Entry.first.print(Total, OS);
  277. OS << Entry.second << '\n';
  278. }
  279. Total.print(Total, OS);
  280. OS << "Total\n\n";
  281. OS.flush();
  282. TimersToPrint.clear();
  283. }
  284. /// print - Print any started timers in this group and zero them.
  285. void TimerGroup::print(raw_ostream &OS) {
  286. sys::SmartScopedLock<true> L(*TimerLock);
  287. // See if any of our timers were started, if so add them to TimersToPrint and
  288. // reset them.
  289. for (Timer *T = FirstTimer; T; T = T->Next) {
  290. if (!T->hasTriggered()) continue;
  291. TimersToPrint.emplace_back(T->Time, T->Name);
  292. // Clear out the time.
  293. T->clear();
  294. }
  295. // If any timers were started, print the group.
  296. if (!TimersToPrint.empty())
  297. PrintQueuedTimers(OS);
  298. }
  299. /// printAll - This static method prints all timers and clears them all out.
  300. void TimerGroup::printAll(raw_ostream &OS) {
  301. sys::SmartScopedLock<true> L(*TimerLock);
  302. for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
  303. TG->print(OS);
  304. }