#include "Stopwatch.h" #include "vcpkg_Checks.h" namespace vcpkg { Stopwatch Stopwatch::createUnstarted() { return Stopwatch(); } Stopwatch Stopwatch::createStarted() { return Stopwatch().start(); } bool Stopwatch::isRunning() const { return this->m_isRunning; } const Stopwatch& Stopwatch::start() { Checks::check_exit(!this->m_isRunning, "This stopwatch is already running."); this->m_isRunning = true; this->m_startTick = std::chrono::high_resolution_clock::now(); return *this; } const Stopwatch& Stopwatch::stop() { auto tick = std::chrono::high_resolution_clock::now(); Checks::check_exit(this->m_isRunning, "This stopwatch is already stopped."); this->m_isRunning = false; this->m_elapsedNanos += tick - this->m_startTick; return *this; } Stopwatch& Stopwatch::reset() { this->m_elapsedNanos = std::chrono::nanoseconds(); this->m_isRunning = false; return *this; } std::string Stopwatch::toString() const { using std::chrono::hours; using std::chrono::minutes; using std::chrono::seconds; using std::chrono::milliseconds; using std::chrono::microseconds; using std::chrono::nanoseconds; using std::chrono::duration_cast; auto nanos = elapsedNanos(); auto nanos_as_double = static_cast(nanos.count()); if (duration_cast(nanos) > hours()) { auto t = nanos_as_double / duration_cast(hours(1)).count(); return Strings::format("%.4g h", t); } if (duration_cast(nanos) > minutes()) { auto t = nanos_as_double / duration_cast(minutes(1)).count(); return Strings::format("%.4g min", t); } if (duration_cast(nanos) > seconds()) { auto t = nanos_as_double / duration_cast(seconds(1)).count(); return Strings::format("%.4g s", t); } if (duration_cast(nanos) > milliseconds()) { auto t = nanos_as_double / duration_cast(milliseconds(1)).count(); return Strings::format("%.4g ms", t); } if (duration_cast(nanos) > microseconds()) { auto t = nanos_as_double / duration_cast(microseconds(1)).count(); return Strings::format("%.4g micros", t); } return Strings::format("%.4g ns", nanos_as_double); } Stopwatch::Stopwatch() : m_isRunning(false), m_elapsedNanos(), m_startTick() { } std::chrono::nanoseconds Stopwatch::elapsedNanos() const { if (this->m_isRunning) { return std::chrono::high_resolution_clock::now() - this->m_startTick + this->m_elapsedNanos; } return this->m_elapsedNanos; } }