xref: /llvm-project-15.0.7/lld/Common/Timer.cpp (revision cc5c65b2)
1 #include "lld/Common/Timer.h"
2 #include "lld/Common/ErrorHandler.h"
3 #include "llvm/Support/Format.h"
4 
5 using namespace lld;
6 using namespace llvm;
7 
8 ScopedTimer::ScopedTimer(Timer &T) : T(&T) { T.start(); }
9 
10 void ScopedTimer::stop() {
11   if (!T)
12     return;
13   T->stop();
14   T = nullptr;
15 }
16 
17 ScopedTimer::~ScopedTimer() { stop(); }
18 
19 Timer::Timer(llvm::StringRef Name) : Name(Name), Parent(nullptr) {}
20 Timer::Timer(llvm::StringRef Name, Timer &Parent)
21     : Name(Name), Parent(&Parent) {}
22 
23 void Timer::start() {
24   if (Parent && Total.count() == 0)
25     Parent->Children.push_back(this);
26   StartTime = std::chrono::high_resolution_clock::now();
27 }
28 
29 void Timer::stop() {
30   Total += (std::chrono::high_resolution_clock::now() - StartTime);
31 }
32 
33 Timer &Timer::root() {
34   static Timer RootTimer("Total Link Time");
35   return RootTimer;
36 }
37 
38 void Timer::print() {
39   double TotalDuration = static_cast<double>(root().millis());
40 
41   // We want to print the grand total under all the intermediate phases, so we
42   // print all children first, then print the total under that.
43   for (const auto &Child : Children)
44     Child->print(1, TotalDuration);
45 
46   message(std::string(49, '-'));
47 
48   root().print(0, root().millis(), false);
49 }
50 
51 double Timer::millis() const {
52   return std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(
53              Total)
54       .count();
55 }
56 
57 void Timer::print(int Depth, double TotalDuration, bool Recurse) const {
58   double P = 100.0 * millis() / TotalDuration;
59 
60   SmallString<32> Str;
61   llvm::raw_svector_ostream Stream(Str);
62   std::string S = std::string(Depth * 2, ' ') + Name + std::string(":");
63   Stream << format("%-30s%5d ms (%5.1f%%)", S.c_str(), (int)millis(), P);
64 
65   message(Str);
66 
67   if (Recurse) {
68     for (const auto &Child : Children)
69       Child->print(Depth + 1, TotalDuration);
70   }
71 }
72