#pragma once
#include <cmath>
#include <wtf/MonotonicTime.h>
#include <wtf/RefCounted.h>
namespace WTF {
class Stopwatch : public RefCounted<Stopwatch> {
public:
static Ref<Stopwatch> create()
{
return adoptRef(*new Stopwatch());
}
void reset();
void start();
void stop();
Seconds elapsedTime();
Seconds elapsedTimeSince(MonotonicTime);
bool isActive() const { return !std::isnan(m_lastStartTime); }
private:
Stopwatch() { reset(); }
Seconds m_elapsedTime;
MonotonicTime m_lastStartTime;
};
inline void Stopwatch::reset()
{
m_elapsedTime = 0_s;
m_lastStartTime = MonotonicTime::nan();
}
inline void Stopwatch::start()
{
ASSERT_WITH_MESSAGE(std::isnan(m_lastStartTime), "Tried to start the stopwatch, but it is already running.");
m_lastStartTime = MonotonicTime::now();
}
inline void Stopwatch::stop()
{
ASSERT_WITH_MESSAGE(!std::isnan(m_lastStartTime), "Tried to stop the stopwatch, but it is not running.");
m_elapsedTime += MonotonicTime::now() - m_lastStartTime;
m_lastStartTime = MonotonicTime::nan();
}
inline Seconds Stopwatch::elapsedTime()
{
if (!isActive())
return m_elapsedTime;
return m_elapsedTime + (MonotonicTime::now() - m_lastStartTime);
}
inline Seconds Stopwatch::elapsedTimeSince(MonotonicTime timeStamp)
{
if (!isActive())
return m_elapsedTime;
return m_elapsedTime + (timeStamp - m_lastStartTime);
}
}
using WTF::Stopwatch;