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

source code of lld/Common/Timer.cpp