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