Timer.cpp 13 KB

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