Loading...
Searching...
No Matches
timer.hh
Go to the documentation of this file.
// -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
// vi: set et ts=4 sw=2 sts=2:
// SPDX-FileCopyrightInfo: Copyright © DUNE Project contributors, see file LICENSE.md in module root
// SPDX-License-Identifier: LicenseRef-GPL-2.0-only-with-DUNE-exception
#ifndef DUNE_TIMER_HH
#define DUNE_TIMER_HH
#include <chrono>
namespace Dune {
class Timer
{
using Clock = std::chrono::high_resolution_clock;
using Units = std::chrono::duration<double>; // seconds stored as double
public:
Timer (bool startImmediately=true) noexcept
{
isRunning_ = startImmediately;
reset();
}
void reset() noexcept
{
sumElapsed_ = std::chrono::seconds{0};
storedLastElapsed_ = std::chrono::seconds{0};
cstart = Clock::now();
}
void start() noexcept
{
if (not (isRunning_))
{
cstart = Clock::now();
isRunning_ = true;
}
}
double elapsed () const noexcept
{
return durationCast(rawElapsed());
}
double lastElapsed () const noexcept
{
return durationCast(rawLastElapsed());
}
double stop() noexcept
{
if (isRunning_)
{
// update storedLastElapsed_ and sumElapsed_ and stop timer
storedLastElapsed_ = rawLastElapsed();
sumElapsed_ += storedLastElapsed_;
isRunning_ = false;
}
return elapsed();
}
private:
bool isRunning_;
Clock::duration sumElapsed_;
Clock::duration storedLastElapsed_;
Clock::duration rawElapsed () const noexcept
{
// if timer is running add the time elapsed since last start to sum
if (isRunning_)
return sumElapsed_ + rawLastElapsed();
return sumElapsed_;
}
Clock::duration rawLastElapsed () const noexcept
{
// if timer is running return the current value
if (isRunning_)
return Clock::now() - cstart;
// if timer is not running return stored value from last run
return storedLastElapsed_;
}
double durationCast(Clock::duration duration) const noexcept {
return std::chrono::duration_cast<Units>(duration).count();
}
Clock::time_point cstart;
}; // end class Timer
} // end namespace
#endif
Dune
Dune namespace
Definition alignedallocator.hh:13
Dune::Timer::reset
void reset() noexcept
Reset timer while keeping the running/stopped state.
Definition timer.hh:47
Dune::Timer::stop
double stop() noexcept
Stop the timer and return elapsed().
Definition timer.hh:79
Dune::Timer::Timer
Timer(bool startImmediately=true) noexcept
A new timer, create and reset.
Definition timer.hh:40
Dune::Timer::elapsed
double elapsed() const noexcept
Get elapsed user-time from last reset until now/last stop in seconds.
Definition timer.hh:67
Dune::Timer::lastElapsed
double lastElapsed() const noexcept
Get elapsed user-time from last start until now/last stop in seconds.
Definition timer.hh:73
Dune::Timer::start
void start() noexcept
Start the timer and continue measurement if it is not running. Otherwise do nothing.
Definition timer.hh:56