xref: /llvm-project-15.0.7/lld/Common/Timer.cpp (revision b4fa71ee)
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) {
17   startTime = std::chrono::high_resolution_clock::now();
18 }
19 
20 void ScopedTimer::stop() {
21   if (!t)
22     return;
23   t->addToTotal(std::chrono::high_resolution_clock::now() - startTime);
24   t = nullptr;
25 }
26 
27 ScopedTimer::~ScopedTimer() { stop(); }
28 
29 Timer::Timer(llvm::StringRef name) : name(std::string(name)) {}
30 Timer::Timer(llvm::StringRef name, Timer &parent) : name(std::string(name)) {
31   parent.children.push_back(this);
32 }
33 
34 void Timer::print() {
35   double totalDuration = static_cast<double>(millis());
36 
37   // We want to print the grand total under all the intermediate phases, so we
38   // print all children first, then print the total under that.
39   for (const auto &child : children)
40     if (child->total > 0)
41       child->print(1, totalDuration);
42 
43   message(std::string(50, '-'));
44 
45   print(0, millis(), false);
46 }
47 
48 double Timer::millis() const {
49   return std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(
50              std::chrono::nanoseconds(total))
51       .count();
52 }
53 
54 void Timer::print(int depth, double totalDuration, bool recurse) const {
55   double p = 100.0 * millis() / totalDuration;
56 
57   SmallString<32> str;
58   llvm::raw_svector_ostream stream(str);
59   std::string s = std::string(depth * 2, ' ') + name + std::string(":");
60   stream << format("%-30s%7d ms (%5.1f%%)", s.c_str(), (int)millis(), p);
61 
62   message(str);
63 
64   if (recurse) {
65     for (const auto &child : children)
66       if (child->total > 0)
67         child->print(depth + 1, totalDuration);
68   }
69 }
70