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