97 lines
1.3 KiB
C++
97 lines
1.3 KiB
C++
// License: Modified MIT (NON-AI)
|
|
// See the LICENSE file in the root directory for license information.
|
|
// Copyright 2025 Timothy Prepscius
|
|
|
|
#pragma once
|
|
|
|
#include "Timer.h"
|
|
#include <chrono>
|
|
#include <thread>
|
|
|
|
#include "../containers/Optional.hpp"
|
|
#include "../assert/debug_assert.h"
|
|
|
|
namespace tjp::core {
|
|
|
|
class Timer
|
|
{
|
|
public:
|
|
typedef double Time;
|
|
typedef double Duration;
|
|
|
|
Duration accumulator = 0;
|
|
Optional<std::chrono::time_point<std::chrono::high_resolution_clock>> then;
|
|
|
|
Timer()
|
|
{
|
|
start();
|
|
}
|
|
|
|
Timer(bool start_)
|
|
{
|
|
if (start_)
|
|
start();
|
|
}
|
|
|
|
auto now() const
|
|
{
|
|
return std::chrono::high_resolution_clock::now();
|
|
}
|
|
|
|
void start()
|
|
{
|
|
debug_assert(!then);
|
|
|
|
accumulator = 0;
|
|
then = now();
|
|
}
|
|
|
|
void restart()
|
|
{
|
|
then.reset();
|
|
start();
|
|
}
|
|
|
|
bool running ()
|
|
{
|
|
return then.has_value();
|
|
}
|
|
|
|
Duration elapsed() const
|
|
{
|
|
if (!then)
|
|
return accumulator;
|
|
|
|
auto now_ = now();
|
|
auto duration = std::chrono::duration<double>(now_ - *then).count();
|
|
|
|
return duration + accumulator;
|
|
}
|
|
|
|
void pause()
|
|
{
|
|
if (!then)
|
|
return ;
|
|
|
|
auto now_ = now();
|
|
auto partial = std::chrono::duration<double>(now_ - *then).count();
|
|
then.reset();
|
|
accumulator += partial;
|
|
}
|
|
|
|
Duration stop()
|
|
{
|
|
pause();
|
|
return accumulator;
|
|
}
|
|
|
|
void resume()
|
|
{
|
|
debug_assert(!then);
|
|
|
|
then = now();
|
|
}
|
|
};
|
|
|
|
} // namespace
|