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