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