Timer.cpp 13 KB

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