Timer.cpp 12 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. 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. // CreateInfoOutputFile - Return a file stream to print our output on.
  49. raw_ostream *llvm::CreateInfoOutputFile() {
  50. const std::string &OutputFilename = getLibSupportInfoOutputFilename();
  51. if (OutputFilename.empty())
  52. return new raw_fd_ostream(2, false); // stderr.
  53. if (OutputFilename == "-")
  54. return new raw_fd_ostream(1, false); // stdout.
  55. // Append mode is used because the info output file is opened and closed
  56. // each time -stats or -time-passes wants to print output to it. To
  57. // compensate for this, the test-suite Makefiles have code to delete the
  58. // info output file before running commands which write to it.
  59. std::error_code EC;
  60. raw_ostream *Result = new raw_fd_ostream(OutputFilename, EC,
  61. sys::fs::F_Append | sys::fs::F_Text);
  62. if (!EC)
  63. return Result;
  64. errs() << "Error opening info-output-file '"
  65. << OutputFilename << " for appending!\n";
  66. delete Result;
  67. return new raw_fd_ostream(2, false); // stderr.
  68. }
  69. #define DefaultTimerGroupName "Miscellaneous Ungrouped Timers"
  70. static TimerGroup DefaultTimerGroup(DefaultTimerGroupName); // HLSL Change - global init
  71. static TimerGroup *getDefaultTimerGroup() {
  72. #if 1 // HLSL Change Starts - global with special clean-up and init
  73. return &DefaultTimerGroup;
  74. #else
  75. TimerGroup *tmp = DefaultTimerGroup;
  76. sys::MemoryFence();
  77. if (tmp) return tmp;
  78. sys::SmartScopedLock<true> Lock(*TimerLock);
  79. tmp = DefaultTimerGroup;
  80. if (!tmp) {
  81. tmp = new TimerGroup("Miscellaneous Ungrouped Timers");
  82. sys::MemoryFence();
  83. DefaultTimerGroup = tmp;
  84. }
  85. return tmp;
  86. #endif // HLSL Change Ends
  87. }
  88. //===----------------------------------------------------------------------===//
  89. // Timer Implementation
  90. //===----------------------------------------------------------------------===//
  91. void Timer::init(StringRef N) {
  92. assert(!TG && "Timer already initialized");
  93. Name.assign(N.begin(), N.end());
  94. Started = false;
  95. TG = getDefaultTimerGroup();
  96. TG->addTimer(*this);
  97. }
  98. void Timer::init(StringRef N, TimerGroup &tg) {
  99. assert(!TG && "Timer already initialized");
  100. Name.assign(N.begin(), N.end());
  101. Started = false;
  102. TG = &tg;
  103. TG->addTimer(*this);
  104. }
  105. Timer::~Timer() {
  106. if (!TG) return; // Never initialized, or already cleared.
  107. TG->removeTimer(*this);
  108. }
  109. static inline size_t getMemUsage() {
  110. if (!TrackSpace) return 0;
  111. return sys::Process::GetMallocUsage();
  112. }
  113. TimeRecord TimeRecord::getCurrentTime(bool Start) {
  114. TimeRecord Result;
  115. sys::TimeValue now(0,0), user(0,0), sys(0,0);
  116. if (Start) {
  117. Result.MemUsed = getMemUsage();
  118. sys::Process::GetTimeUsage(now, user, sys);
  119. } else {
  120. sys::Process::GetTimeUsage(now, user, sys);
  121. Result.MemUsed = getMemUsage();
  122. }
  123. Result.WallTime = now.seconds() + now.microseconds() / 1000000.0;
  124. Result.UserTime = user.seconds() + user.microseconds() / 1000000.0;
  125. Result.SystemTime = sys.seconds() + sys.microseconds() / 1000000.0;
  126. return Result;
  127. }
  128. static ManagedStatic<std::vector<Timer*> > ActiveTimers;
  129. void Timer::startTimer() {
  130. Started = true;
  131. ActiveTimers->push_back(this);
  132. Time -= TimeRecord::getCurrentTime(true);
  133. }
  134. void Timer::stopTimer() {
  135. Time += TimeRecord::getCurrentTime(false);
  136. if (ActiveTimers->back() == this) {
  137. ActiveTimers->pop_back();
  138. } else {
  139. std::vector<Timer*>::iterator I =
  140. std::find(ActiveTimers->begin(), ActiveTimers->end(), this);
  141. assert(I != ActiveTimers->end() && "stop but no startTimer?");
  142. ActiveTimers->erase(I);
  143. }
  144. }
  145. static void printVal(double Val, double Total, raw_ostream &OS) {
  146. if (Total < 1e-7) // Avoid dividing by zero.
  147. OS << " ----- ";
  148. else
  149. OS << format(" %7.4f (%5.1f%%)", Val, Val*100/Total);
  150. }
  151. void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const {
  152. if (Total.getUserTime())
  153. printVal(getUserTime(), Total.getUserTime(), OS);
  154. if (Total.getSystemTime())
  155. printVal(getSystemTime(), Total.getSystemTime(), OS);
  156. if (Total.getProcessTime())
  157. printVal(getProcessTime(), Total.getProcessTime(), OS);
  158. printVal(getWallTime(), Total.getWallTime(), OS);
  159. OS << " ";
  160. if (Total.getMemUsed())
  161. OS << format("%9" PRId64 " ", (int64_t)getMemUsed());
  162. }
  163. //===----------------------------------------------------------------------===//
  164. // NamedRegionTimer Implementation
  165. //===----------------------------------------------------------------------===//
  166. namespace {
  167. typedef StringMap<Timer> Name2TimerMap;
  168. class Name2PairMap {
  169. StringMap<std::pair<TimerGroup*, Name2TimerMap> > Map;
  170. public:
  171. ~Name2PairMap() {
  172. for (StringMap<std::pair<TimerGroup*, Name2TimerMap> >::iterator
  173. I = Map.begin(), E = Map.end(); I != E; ++I)
  174. delete I->second.first;
  175. }
  176. Timer &get(StringRef Name, StringRef GroupName) {
  177. sys::SmartScopedLock<true> L(*TimerLock);
  178. std::pair<TimerGroup*, Name2TimerMap> &GroupEntry = Map[GroupName];
  179. if (!GroupEntry.first)
  180. GroupEntry.first = new TimerGroup(GroupName);
  181. Timer &T = GroupEntry.second[Name];
  182. if (!T.isInitialized())
  183. T.init(Name, *GroupEntry.first);
  184. return T;
  185. }
  186. };
  187. }
  188. static ManagedStatic<Name2TimerMap> NamedTimers;
  189. static ManagedStatic<Name2PairMap> NamedGroupedTimers;
  190. static Timer &getNamedRegionTimer(StringRef Name) {
  191. sys::SmartScopedLock<true> L(*TimerLock);
  192. Timer &T = (*NamedTimers)[Name];
  193. if (!T.isInitialized())
  194. T.init(Name);
  195. return T;
  196. }
  197. NamedRegionTimer::NamedRegionTimer(StringRef Name,
  198. bool Enabled)
  199. : TimeRegion(!Enabled ? nullptr : &getNamedRegionTimer(Name)) {}
  200. NamedRegionTimer::NamedRegionTimer(StringRef Name, StringRef GroupName,
  201. bool Enabled)
  202. : TimeRegion(!Enabled ? nullptr : &NamedGroupedTimers->get(Name, GroupName)){}
  203. //===----------------------------------------------------------------------===//
  204. // TimerGroup Implementation
  205. //===----------------------------------------------------------------------===//
  206. /// TimerGroupList - This is the global list of TimerGroups, maintained by the
  207. /// TimerGroup ctor/dtor and is protected by the TimerLock lock.
  208. static TimerGroup *TimerGroupList = nullptr;
  209. TimerGroup::TimerGroup(StringRef name)
  210. : Name(name.begin(), name.end()), FirstTimer(nullptr) {
  211. // HLSL Change Starts - initialize as head without locking
  212. if (name.equals(DefaultTimerGroupName)) {
  213. Next = TimerGroupList;
  214. Prev = &TimerGroupList;
  215. TimerGroupList = this;
  216. return;
  217. }
  218. // HLSL Change Ends
  219. // Add the group to TimerGroupList.
  220. sys::SmartScopedLock<true> L(*TimerLock);
  221. if (TimerGroupList)
  222. TimerGroupList->Prev = &Next;
  223. Next = TimerGroupList;
  224. Prev = &TimerGroupList;
  225. TimerGroupList = this;
  226. }
  227. TimerGroup::~TimerGroup() {
  228. // If the timer group is destroyed before the timers it owns, accumulate and
  229. // print the timing data.
  230. while (FirstTimer)
  231. removeTimer(*FirstTimer);
  232. // HLSL Change Starts - don't bother cleaning up global
  233. if (this == &DefaultTimerGroup) {
  234. return;
  235. }
  236. // HLSL Change Ends
  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 != &DefaultTimerGroup)
  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. }