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 Timer &Timer::root() { 35 static Timer rootTimer("Total Link Time"); 36 return rootTimer; 37 } 38 39 void Timer::print() { 40 double totalDuration = static_cast<double>(root().millis()); 41 42 // We want to print the grand total under all the intermediate phases, so we 43 // print all children first, then print the total under that. 44 for (const auto &child : children) 45 if (child->total > 0) 46 child->print(1, totalDuration); 47 48 message(std::string(50, '-')); 49 50 root().print(0, root().millis(), false); 51 } 52 53 double Timer::millis() const { 54 return std::chrono::duration_cast<std::chrono::duration<double, std::milli>>( 55 std::chrono::nanoseconds(total)) 56 .count(); 57 } 58 59 void Timer::print(int depth, double totalDuration, bool recurse) const { 60 double p = 100.0 * millis() / totalDuration; 61 62 SmallString<32> str; 63 llvm::raw_svector_ostream stream(str); 64 std::string s = std::string(depth * 2, ' ') + name + std::string(":"); 65 stream << format("%-30s%7d ms (%5.1f%%)", s.c_str(), (int)millis(), p); 66 67 message(str); 68 69 if (recurse) { 70 for (const auto &child : children) 71 if (child->total > 0) 72 child->print(depth + 1, totalDuration); 73 } 74 } 75