|
| 1 | +#include "Math/Util.h" |
| 2 | + |
| 3 | +#include <chrono> |
| 4 | + |
| 5 | +ROOT::Math::Util::TimingScope::TimingScope(std::function<void(std::string const &)> printer, std::string const &message) |
| 6 | + : fPrinter{printer}, fMessage{message} |
| 7 | +{ |
| 8 | + using std::chrono::steady_clock; |
| 9 | + fBegin = new steady_clock::time_point{steady_clock::now()}; |
| 10 | +} |
| 11 | + |
| 12 | +namespace { |
| 13 | + |
| 14 | +template <class T> |
| 15 | +std::string printTime(T duration) |
| 16 | +{ |
| 17 | + std::stringstream ss; |
| 18 | + // Here, nanoseconds are represented as "long int", so the maximum value |
| 19 | + // corresponds to about 300 years. Nobody will wait that long for a |
| 20 | + // computation to complete, so for timing measurements it's fine to cast to |
| 21 | + // nanoseconds to keep things simple. |
| 22 | + double ns = std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count(); |
| 23 | + bool forceSeconds = false; |
| 24 | + // The largest unit that we consider for pretty-printing is days. |
| 25 | + if (ns >= 24 * 60 * 60e9) { |
| 26 | + auto days = std::floor(ns / (24 * 60 * 60e9)); |
| 27 | + ss << days << " d "; |
| 28 | + ns -= days * 24 * 60 * 60e9; // subtract the days to print only the rest |
| 29 | + // to avoid printouts like "1 d 4 h 23 min 324 ns", we force to print |
| 30 | + // seconds if we print either days, hours, or minutes |
| 31 | + forceSeconds = true; |
| 32 | + } |
| 33 | + if (ns >= 60 * 60e9) { |
| 34 | + auto hours = std::floor(ns / (60 * 60e9)); |
| 35 | + ss << hours << " h "; |
| 36 | + ns -= hours * 60 * 60e9; |
| 37 | + forceSeconds = true; |
| 38 | + } |
| 39 | + if (ns >= 60e9) { |
| 40 | + auto minutes = std::floor(ns / 60e9); |
| 41 | + ss << minutes << " min "; |
| 42 | + ns -= minutes * 60e9; |
| 43 | + forceSeconds = true; |
| 44 | + } |
| 45 | + if (ns >= 1e9 || forceSeconds) { |
| 46 | + ss << (1e-9 * ns) << " s"; |
| 47 | + } else if (ns >= 1e6) { |
| 48 | + ss << (1e-6 * ns) << " ms"; |
| 49 | + } else if (ns >= 1e3) { |
| 50 | + ss << (1e-3 * ns) << " μs"; |
| 51 | + } else { |
| 52 | + ss << ns << " ns"; |
| 53 | + } |
| 54 | + return ss.str(); |
| 55 | +} |
| 56 | + |
| 57 | +} // namespace |
| 58 | + |
| 59 | +ROOT::Math::Util::TimingScope::~TimingScope() |
| 60 | +{ |
| 61 | + using std::chrono::steady_clock; |
| 62 | + auto *begin = reinterpret_cast<steady_clock::time_point *>(fBegin); |
| 63 | + steady_clock::time_point end = steady_clock::now(); |
| 64 | + std::stringstream ss; |
| 65 | + ss << fMessage << " " << printTime(end - *begin); |
| 66 | + fPrinter(ss.str()); |
| 67 | + // fROOT::Math::Util.Info(ss.str()); |
| 68 | + delete begin; |
| 69 | +} |
0 commit comments