vcpkg/toolsrc/src/Stopwatch.cpp

106 lines
3.0 KiB
C++
Raw Normal View History

2017-01-28 04:49:09 +08:00
#include "pch.h"
2016-10-11 09:12:26 +08:00
#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()
2016-10-11 09:12:26 +08:00
{
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()
2016-10-11 09:12:26 +08:00
{
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<double>(nanos.count());
if (duration_cast<hours>(nanos) > hours())
{
auto t = nanos_as_double / duration_cast<nanoseconds>(hours(1)).count();
return Strings::format("%.4g h", t);
}
if (duration_cast<minutes>(nanos) > minutes())
{
auto t = nanos_as_double / duration_cast<nanoseconds>(minutes(1)).count();
return Strings::format("%.4g min", t);
}
if (duration_cast<seconds>(nanos) > seconds())
{
auto t = nanos_as_double / duration_cast<nanoseconds>(seconds(1)).count();
return Strings::format("%.4g s", t);
}
if (duration_cast<milliseconds>(nanos) > milliseconds())
{
auto t = nanos_as_double / duration_cast<nanoseconds>(milliseconds(1)).count();
return Strings::format("%.4g ms", t);
}
if (duration_cast<microseconds>(nanos) > microseconds())
{
auto t = nanos_as_double / duration_cast<nanoseconds>(microseconds(1)).count();
return Strings::format("%.4g us", t);
2016-10-11 09:12:26 +08:00
}
return Strings::format("%.4g ns", nanos_as_double);
}
Stopwatch::Stopwatch() : m_isRunning(false), m_elapsedNanos(0), m_startTick()
2016-10-11 09:12:26 +08:00
{
}
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;
}
}