Overview / System & concurrency

time

Durations, instants, clocks, stopwatch, deadlines, calendar, date formatting and parsing, timers and sleep. A leaf module.

Always compiled: part of the core build.Include #include <ethereal/cpp/time/time_inc.hpp>C layer

time_inc.hpp

#include <ethereal/cpp/time/time_inc.hpp>

Aggregate entry point of the Time module.

Interval, instant, clocks and the time source seam, plus the calendar, formatting, timers and sleep.

Including this header brings the whole module. The individual headers can still be used alone, for those who want to pay only for what they use.

The module is a leaf: it includes no header of any other module of the library. Section 2 of the conventions requires it, and it is what allows measuring time inside any other module without creating a cycle.

civil.hpp

#include <ethereal/cpp/time/civil.hpp>

Civil calendar, date arithmetic and local time zone of the Time module.

The calendar does not go through the C library. The spec forbids 'mktime', 'localtime' and 'gmtime' for four reasons:

  • Locale. Their result depends on global state that another part of the program may have changed.
  • Global state. 'gmtime' returns a pointer to a static buffer that the next call overwrites. Two conversions in the same expression give the same date twice.
  • Threads. For the same reason, two threads converting dates at the same time step on each other. There are '_r' and '_s' variants, and they differ on each platform.
  • Speed. 'mktime' normalizes, looks up the time zone and, in some implementations, loops over years.

The module uses the Howard Hinnant algorithm, which the spec names. It converts a civil date to a count of days since 1970-01-01 with plain arithmetic (no loops, no year tables, no leap year branches) and works for any year that fits the type. The idea is to start the year in March. The leap day then becomes the last day of the year instead of sitting in the middle, and the month lengths become a single expression: '( 153 * m + 2 ) / 5'.

The module does not ship the IANA tz database (see the time zone section below).

struct

SCivilTime

Ethereal::Time#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SCivilTime   final
{
    /// @brief  The year, signed. 2026 is 2026, and 1 BC is 0.
    ETL_INT32    iYear = 1970;

    /// @brief  The month, from 1 to 12. Not from 0 to 11, which is the trap of
    ///          'struct tm'.
    ETL_UINT8    uMonth = 1u;

    /// @brief  The day of the month, from 1 to 31.
    ETL_UINT8    uDay = 1u;

    /// @brief  The hour, from 0 to 23.
    ETL_UINT8    uHour = 0u;

    /// @brief  The minute, from 0 to 59.
    ETL_UINT8    uMinute = 0u;

    /// @brief  The second, from 0 to 59. There is no second 60.
    ///
    /// @details  A leap second has no representation here, by choice: the real
    ///            time clock of the system does not have it either (it repeats
    ///            or stretches a second), and inventing a 60 here would give a
    ///            date that does not convert back to the instant it came from.
    ETL_UINT8    uSecond = 0u;

    /// @brief  The fraction of the second, in nanoseconds.
    ETL_UINT32    uNanos = 0u;


    /// @brief  Field by field equality.
    ETL_API_NOIGN    ETL_INL_CEXPR bool operator == ( const SCivilTime & ) const = default;
};

A civil date and time, field by field.

No time zone. An SCivilTime is a calendar reading and nothing more. The time zone is a separate offset that is added or subtracted, see LocalOffset.

function

DaysFromCivil

Ethereal::Time#
ETL_INT64 DaysFromCivil( ETL_INT32 iYear, ETL_UINT32 uMonth, ETL_UINT32 uDay ) noexcept;
function

CivilFromDays

Ethereal::Time#
void CivilFromDays( ETL_INT64 iDays, ETL_INT32 * pYear, ETL_UINT32 * pMonth, ETL_UINT32 * pDay ) noexcept;

Year, month and day from days since 1970-01-01. The inverse of DaysFromCivil.

iDays
Days since 1970-01-01.
pYear
Receives the year. May be null.
pMonth
Receives the month. May be null.
pDay
Receives the day. May be null.
function

ToCivilUtc

Ethereal::Time#
ETimeError ToCivilUtc( STimePoint When, SCivilTime * pOut ) noexcept;

Converts an instant of the real time clock to a civil date in UTC.

When
The instant.
pOut
Receives the date.
eOk, or eInvalidArgument when pOut is null.
function

FromCivilUtc

Ethereal::Time#
ETimeError FromCivilUtc( const SCivilTime & Civil, STimePoint * pOut ) noexcept;

Converts a civil date in UTC to an instant of the real time clock.

The fields are checked: a month 13 or a February 31 give eInvalidArgument instead of a silently normalized date. Normalizing is what 'mktime' does, and it is how a typo becomes a valid date that nobody notices.

Civil
The date.
pOut
Receives the instant.
eOk, eInvalidArgument for a bad field or a null pOut, or eOverflow when the date does not fit in 64 bit nanoseconds.
function

IsLeapYear

Ethereal::Time#
inline constexpr bool IsLeapYear( const ETL_INT32 iYear ) noexcept

Tells whether the year is a leap year. Arithmetic, not a table.

iYear
The year.
true for a leap year.
function

DaysInMonth

Ethereal::Time#
ETL_UINT32 DaysInMonth( ETL_INT32 iYear, ETL_UINT32 uMonth ) noexcept;

How many days the month has.

iYear
The year.
uMonth
The month.
The number of days. Zero when the month is not from 1 to 12.
function

WeekdayFromDays

Ethereal::Time#
ETL_UINT32 WeekdayFromDays( ETL_INT64 iDays ) noexcept;

The day of the week of a day count: 0 is Sunday, 6 is Saturday.

iDays
Days since 1970-01-01.
The day of the week.
function

Weekday

Ethereal::Time#
ETL_UINT32 Weekday( const SCivilTime & Civil ) noexcept;

The day of the week of a date: 0 is Sunday, 6 is Saturday.

Civil
The date.
The day of the week.
function

DayOfYear

Ethereal::Time#
ETL_UINT32 DayOfYear( const SCivilTime & Civil ) noexcept;

The day of the year, starting at 1.

Civil
The date.
The day of the year.
function

IsoWeek

Ethereal::Time#
void IsoWeek( const SCivilTime & Civil, ETL_UINT32 * pWeek, ETL_INT32 * pWeekYear ) noexcept;

The ISO 8601 week, from 1 to 53, and the year it belongs to.

The year of the ISO week is not always the year of the date, and that is the part everybody gets wrong: 2027-01-01 is a Friday and belongs to week 53 of 2026. The rule is that a week belongs to the year that holds four or more of its days, and weeks start on Monday.

Civil
The date.
pWeek
Receives the week. May be null.
pWeekYear
Receives the year of the week. May be null.
function

AddDays

Ethereal::Time#
SCivilTime AddDays( const SCivilTime & Civil, ETL_INT64 iDays ) noexcept;

Adds days to a date. Exact, and with no loop.

Civil
The date.
iDays
How many days to add. Can be negative.
The new date. The time of day is kept.
function

AddMonths

Ethereal::Time#
SCivilTime AddMonths( const SCivilTime & Civil, ETL_INT64 iMonths ) noexcept;

Adds months to a date, clamping the day to the end of the month.

January 31 plus one month gives February 28 (or 29), not March 3. There is no right answer here, only a chosen one. Clamping is what almost everybody expects and what the spec asks for ("add months with clamping"), and it is written down so nobody finds out by accident.

Note that this is not reversible: adding one month to January 31 and then subtracting one month gives January 28.

Civil
The date.
iMonths
How many months to add. Can be negative.
The new date.
function

LocalOffset

Ethereal::Time#
SDuration LocalOffset() noexcept;

How far local time is ahead of UTC, now.

Positive east of Greenwich. Includes daylight saving time when it is in effect.

The value is cached, because asking the system costs much more than a calendar conversion. See RefreshTimezone.

function

IsDaylightSaving

Ethereal::Time#
bool IsDaylightSaving() noexcept;

Tells whether daylight saving time is in effect now.

function

RefreshTimezone

Ethereal::Time#
void RefreshTimezone() noexcept;

Drops the cached value and asks the system again.

It is explicit on purpose, and the spec asks for it. The cached value goes stale in two ways: daylight saving starts or ends, or someone changes the time zone of the machine. Neither notifies the process, and refreshing on every read would pay the cost always for the rare case.

function

ToCivilLocal

Ethereal::Time#
ETimeError ToCivilLocal( STimePoint When, SCivilTime * pOut ) noexcept;

Converts an instant to a civil date in local time.

When
The instant.
pOut
Receives the date.
eOk, or eInvalidArgument when pOut is null.

clock.hpp

#include <ethereal/cpp/time/clock.hpp>

Instants, clock reading and the time source seam of the Time module.

STimePoint is an instant in nanoseconds tagged with the clock that produced it. Instants of different clocks do not compare or subtract: the monotonic clock counts from an arbitrary mark and never goes back, the wall clock counts from the Epoch and can jump when the system sets the time.

Also provides the clock reading functions (monotonic, wall, process and thread CPU time, the raw cycle counter), the capability queries and IClock, the seam that lets other modules be tested with a manual clock.

enum

EClockKind

Ethereal::Time#
C++
enum class   EClockKind : ETL_UINT8
{
    /// @brief  Steady clock. Never goes back and is not affected by time changes.
    ///
    /// @details  The only one that can measure an interval. Its zero mark is
    ///            arbitrary and changes on every boot, so the absolute value
    ///            means nothing on its own.
    Monotonic = 0,

    /// @brief  Wall clock, counted from the Epoch (1970-01-01 in UTC).
    ///
    /// @details  The only one that tells what time it is. It can jump forward
    ///            and back when the system sets the time, so measuring an interval
    ///            with it gives wrong numbers, including negative ones.
    Realtime = 1,

    /// @brief  Processor time consumed by this process.
    Process = 2,

    /// @brief  Processor time consumed by this thread.
    Thread = 3
};

Which clock produced an instant.

The tag travels inside the instant because instants of different clocks do not compare or subtract: the monotonic clock counts from an arbitrary mark and never goes back, the wall clock counts from the Epoch and can jump when the system sets the time.

struct

STimePoint

Ethereal::Time#
C++
struct   STimePoint   final
{
    /// @brief  The count, in nanoseconds, since the mark of the clock.
    ETL_INT64 iNanos = 0;

    /// @brief  Which clock produced this count.
    EClockKind eKind = EClockKind::Monotonic;


    /// @brief  Total order.
    ///
    /// @warning  Only meaningful between instants of the same clock. Between
    ///            different clocks the comparison still compiles and returns a
    ///            meaningless result: the zero marks are unrelated.
    ///
    ETL_API_NOIGN    ETL_INL_CEXPR auto operator <=> ( const STimePoint & ) const = default;

    /// @brief  Equality. Compares the count and the tag.
    ETL_API_NOIGN    ETL_INL_CEXPR bool operator ==  ( const STimePoint & ) const = default;
};

An instant, tagged with the clock that produced it.

Sixteen bytes and trivially copyable: eight of count, one of tag, and the padding the alignment requires.

The count is already in nanoseconds. The conversion from the raw unit of the platform happens once, on reading, and not on every later computation. That way all instant and interval arithmetic uses the same unit.

Thread safety: full. It is a value and holds no state.
operator

operator-

Ethereal::Time#
inline constexpr SDuration operator - ( STimePoint Later, STimePoint Earlier ) noexcept

How much time separates two instants.

Precondition: both come from the same clock. This operator does not check, because it is the hot path and checking would cost a branch per call.

The package spec asks for "a compile error where possible, an assertion elsewhere". There is no compile error here because the tag is a field and not a type parameter (the package asks for 16 bytes with the tag inside). There is no assertion because ETL_ASSERT lives in the Assert module, and section 2 of the conventions forbids a module from including another module's header to get functionality.

Instead there is Difference, which returns an error when the tags disagree. That is stronger than an assertion: an assertion disappears in release, the returned check does not.

Later
The most recent instant.
Earlier
The oldest instant.
The difference. Negative when Later actually came first.
function

Difference

Ethereal::Time#
inline constexpr ETimeError Difference( STimePoint Later, STimePoint Earlier, SDuration & ResultOut ) noexcept

How much time separates two instants, refusing different clocks.

Later
The most recent instant.
Earlier
The oldest instant.
ResultOut
Receives the difference. Untouched on failure.
ETimeError::eOk, ETimeError::eInvalidArgument when the tags disagree, or ETimeError::eOverflow.
Does not allocate. Thread safety: full.
operator

operator+

Ethereal::Time#
inline constexpr STimePoint operator + ( STimePoint Point, SDuration Delta ) noexcept

An instant moved forward by an interval.

operator

operator+

Ethereal::Time#
inline constexpr STimePoint operator + ( SDuration Delta, STimePoint Point ) noexcept

An instant moved forward by an interval, with the operands swapped.

operator

operator-

Ethereal::Time#
inline constexpr STimePoint operator - ( STimePoint Point, SDuration Delta ) noexcept

An instant moved back by an interval.

function

NowMonotonic

Ethereal::Time#
STimePoint NowMonotonic() noexcept;

The current instant of the steady clock.

The most called function of the library: it sits in the inner loop of the profiler, of logging and of every rate computation.

It does not allocate, does not lock and does not take a slow path into the system. On Linux and macOS the reading goes through the vDSO, which resolves it in user space without a system call. Use UsesVdso to check instead of assuming. On Windows it uses the high resolution counter, with the frequency read once and converted by integer multiplication.

The function is not inline: making it inline would bring '<windows.h>' into a public header, which poisons every unit that includes this file. The cost of the call is measured and recorded in the module README.

The instant, tagged as EClockKind::Monotonic.
Thread safety: full.
function

NowRealtime

Ethereal::Time#
STimePoint NowRealtime() noexcept;

The current instant of the wall clock, counted from the Epoch.

The instant, tagged as EClockKind::Realtime.
Thread safety: full.
It can jump forward and back when the system sets the time. Do not use it to measure an interval: that is what NowMonotonic is for.
function

ProcessCpuTime

Ethereal::Time#
SDuration ProcessCpuTime() noexcept;

Processor time consumed by this process, all threads added.

The total consumed. Zero when the platform cannot tell.
Thread safety: full.
function

ThreadCpuTime

Ethereal::Time#
SDuration ThreadCpuTime() noexcept;

Processor time consumed by the calling thread.

The total consumed. Zero when the platform cannot tell.
Thread safety: full. Each caller sees its own thread.
function

Rdtsc

Ethereal::Time#
ETL_UINT64 Rdtsc() noexcept;

The raw cycle counter of the processor.

The raw count. Outside x86 it returns the equivalent counter of the architecture, and zero where there is none.
Thread safety: full.
This is not a clock. On a machine without an invariant TSC the count changes pace with the frequency and is not synchronized between cores, so two values read on different cores can even go backwards. Check HasInvariantTsc before drawing timing conclusions, and prefer NowMonotonic for anything other than micro measurements inside a single core.
function

ClockResolution

Ethereal::Time#
SDuration ClockResolution( EClockKind eKind ) noexcept;

The smallest step a clock can distinguish.

eKind
Which clock.
The resolution reported by the platform. Zero when it cannot tell.
Thread safety: full.
function

HasInvariantTsc

Ethereal::Time#
bool HasInvariantTsc() noexcept;

Tells whether the cycle counter runs at a constant pace.

Read from CPUID, leaf 0x80000007, bit 8 of EDX. Outside x86 it returns false, because the question does not apply the same way.

true when the TSC is invariant.
Thread safety: full. The value is computed once.
function

UsesVdso

Ethereal::Time#
bool UsesVdso() noexcept;

Tells whether reading the time resolves in user space, without the kernel.

The package spec requires that the reading does not silently fall back to a system call. This query exists to make that fall back visible: when it returns false, the reading costs a system call and whoever measures needs to know.

On Windows it returns true: the high resolution counter already resolves in user space. On Linux it checks for the vDSO.

true when the reading avoids the kernel.
Thread safety: full. The value is computed once.
struct

IClock

Ethereal::Time#
C++
struct   IClock
{
    /// @brief  The current instant, according to this source.
    virtual STimePoint Now() ETL_NOEXCEPT = 0;

    /// @brief  The smallest step this source distinguishes.
    virtual SDuration Resolution() ETL_NOEXCEPT = 0;

    /// @brief  Virtual destructor. Ownership belongs to the creator.
    virtual ~IClock() = default;
};

Time source seam, for code that needs to swap the clock.

The seam is crossed once per logical operation, never inside a loop: code that reads the time in a loop calls NowMonotonic directly, which has no virtual dispatch.

It exists so that Stats, Http, Profiler, Log, Concurrency, Resilience and Cache can be tested without depending on the wall clock.

Thread safety: depends on the implementation. The real one is full.
function

SystemClock

Ethereal::Time#
IClock * SystemClock() noexcept;

The real time source, wired to NowMonotonic.

Pointer to an instance with static lifetime. It is not meant to be destroyed, which is why the function is not called Create.
Thread safety: full.
class

CManualClock

Ethereal::Time#

Time source moved by hand, for deterministic tests.

class CManualClock final : public IClock

Touches no system clock. Time only moves when someone calls Advance, which makes any test that depends on a deadline, an expiry or a rate reproducible.

Thread safety: none. Callers using it from more than one thread serialize.
constructor

CManualClock

#
CManualClock() noexcept = default;

Builds the source stopped at instant zero.

constructor

CManualClock

#
explicit CManualClock( STimePoint Start ) noexcept : m_Now( Start )

Builds the source stopped at a chosen instant.

Start
The initial instant.
function

Now

#
STimePoint Now() noexcept override

The instant at which the source is stopped.

function

Resolution

#
SDuration Resolution() noexcept override

The declared resolution of this source: one nanosecond.

function

Advance

#
void Advance( SDuration Delta ) noexcept

Moves time forward.

Delta
How much to move. Can be negative, to exercise the case of a clock that jumps back.
function

SetNow

#
void SetNow( STimePoint Point ) noexcept

Puts the source at a chosen instant.

Point
The new instant.

deadline.hpp

#include <ethereal/cpp/time/deadline.hpp>
class

CDeadline

Ethereal::Time#

A deadline: the instant after which an operation is no longer worth it.

class CDeadline final

Eight bytes and trivially copyable, on purpose: it is made to be passed by value down whole call chains, through Rpc, Http and Resilience, with no indirection cost.

It stores the absolute expiry instant, not the time left. The difference matters: storing the time left, every layer receiving it would have to subtract its own processing time, and the deadline would stretch at every hop.

The clock is always the steady one. A deadline counted on the wall clock expires at the wrong time when the system sets the time.

Thread safety: full. It is a value and holds no mutable state.
constructor

CDeadline

#
CDeadline() noexcept = default;

Builds a deadline that never expires.

It is the neutral value of Tighten: combining "no deadline" with any other gives the other. Without it, code with no deadline would have to carry a separate boolean down the whole chain.

function

After

#
static CDeadline After( SDuration Timeout ) noexcept

Builds a deadline that expires a given time from now.

Timeout
How much time the operation has. A non positive value creates a deadline that already expired, which is what "zero time" means.
The deadline.
function

At

#
static CDeadline At( STimePoint At ) noexcept

Builds a deadline that expires at a given instant.

At
The expiry instant. Precondition: it comes from the steady clock.
The deadline.
function

Never

#
static CDeadline Never() noexcept

Builds the deadline that never expires.

function

Remaining

#
SDuration Remaining() const noexcept

How much time is left.

The time left. Zero when already expired, never negative: the caller uses this as a wait time, and a negative wait does not exist. For the deadline that never expires it returns the largest possible interval.
function

Expired

#
bool Expired() const noexcept

Tells whether the deadline already expired.

There is no IsNever check here, on purpose: the sentinel of the endless deadline is the largest representable instant, and the steady clock would need about 292 years of machine uptime to reach it. The comparison already returns false by itself.

The check existed, and mutation testing showed it was equivalent: removing it changed no test result. A branch nobody can measure rots, so it went away.

Remaining, on the other hand, needs the check: without it the returned value would be 'INT64_MAX minus now', not INT64_MAX.

function

IsNever

#
inline constexpr bool IsNever() const noexcept

Tells whether this is the deadline that never expires.

function

Point

#
inline constexpr STimePoint Point() const noexcept

The expiry instant, on the steady clock.

function

Tighten

#
inline constexpr CDeadline Tighten( CDeadline Other ) const noexcept

The tighter of this deadline and another.

This is what lets a deadline go down a call chain: each layer tightens it with its own limit, and none can loosen the limit of its caller.

Other
The other deadline.
The one that expires first.
operator

operator<=>

#
inline constexpr auto operator <=> ( const CDeadline & ) const = default;

Order and equality, derived from the expiry instant.

operator

operator==

#
inline constexpr bool operator == ( const CDeadline & ) const = default;

Equality, derived from the expiry instant.

duration.hpp

#include <ethereal/cpp/time/duration.hpp>

Signed time interval of the Time module, in nanoseconds.

SDuration is eight bytes, trivially copyable, and all of its arithmetic is constexpr. The normal operators do not check overflow and wrap around through ETL_UINT64. The checked variants (AddChecked, SubChecked, MulChecked, DivChecked, NegateChecked) return ETimeError instead.

Also provides the conversion constants, the constructors per unit, rounding against another unit and the literals.

const

NANOS_PER_MICRO

Ethereal::Time#
inline constexpr ETL_INT64 NANOS_PER_MICRO = 1000LL;

Nanoseconds in a microsecond.

const

NANOS_PER_MILLI

Ethereal::Time#
inline constexpr ETL_INT64 NANOS_PER_MILLI = 1000000LL;

Nanoseconds in a millisecond.

const

NANOS_PER_SECOND

Ethereal::Time#
inline constexpr ETL_INT64 NANOS_PER_SECOND = 1000000000LL;

Nanoseconds in a second.

const

NANOS_PER_MINUTE

Ethereal::Time#
inline constexpr ETL_INT64 NANOS_PER_MINUTE = 60LL * NANOS_PER_SECOND;

Nanoseconds in a minute.

const

NANOS_PER_HOUR

Ethereal::Time#
inline constexpr ETL_INT64 NANOS_PER_HOUR = 60LL * NANOS_PER_MINUTE;

Nanoseconds in an hour.

const

NANOS_PER_DAY

Ethereal::Time#
inline constexpr ETL_INT64 NANOS_PER_DAY = 24LL * NANOS_PER_HOUR;

Nanoseconds in a day.

struct

SDuration

Ethereal::Time#
C++
struct   SDuration   final
{
    /// @brief  The interval, in nanoseconds.
    ETL_INT64 iNanos = 0;


    ///-------------------------------------------------------------------------
    ///  Arithmetic, unchecked
    ///-------------------------------------------------------------------------


    /// @brief  Adds another interval to this one. Wrapping around is defined.
    ///
    ETL_INL_CEXPR SDuration & operator += ( SDuration Other ) ETL_NOEXCEPT
    {
        iNanos = static_cast< ETL_INT64 >( static_cast< ETL_UINT64 >( iNanos )
                                         + static_cast< ETL_UINT64 >( Other.iNanos ) );
        return *this;
    }

    /// @brief  Subtracts another interval from this one. Wrapping around is defined.
    ///
    ETL_INL_CEXPR SDuration & operator -= ( SDuration Other ) ETL_NOEXCEPT
    {
        iNanos = static_cast< ETL_INT64 >( static_cast< ETL_UINT64 >( iNanos )
                                         - static_cast< ETL_UINT64 >( Other.iNanos ) );
        return *this;
    }

    /// @brief  Multiplies this interval by an integer scalar.
    ///
    ETL_INL_CEXPR SDuration & operator *= ( ETL_INT64 iFactor ) ETL_NOEXCEPT
    {
        iNanos = static_cast< ETL_INT64 >( static_cast< ETL_UINT64 >( iNanos )
                                         * static_cast< ETL_UINT64 >( iFactor ) );
        return *this;
    }

    /// @brief  Divides this interval by an integer scalar, truncating towards zero.
    ///
    /// @warning  A zero divisor is undefined behavior, as in any integer division
    ///            of the language. Callers that do not control the value use
    ///            @ref DivChecked.
    ///
    ETL_INL_CEXPR SDuration & operator /= ( ETL_INT64 iDivisor ) ETL_NOEXCEPT
    {
        iNanos /= iDivisor;
        return *this;
    }

    /// @brief  Remainder of the division by another interval.
    ///
    ETL_INL_CEXPR SDuration & operator %= ( SDuration Other ) ETL_NOEXCEPT
    {
        iNanos %= Other.iNanos;
        return *this;
    }


    ///-------------------------------------------------------------------------
    ///  Reading in other units, truncating towards zero
    ///-------------------------------------------------------------------------


    /// @brief  The interval in nanoseconds.
    ETL_API_NOIGN    ETL_INL_CEXPR ETL_INT64 ToNanoseconds()  const ETL_NOEXCEPT { return iNanos; }

    /// @brief  The interval in microseconds, truncated towards zero.
    ETL_API_NOIGN    ETL_INL_CEXPR ETL_INT64 ToMicroseconds() const ETL_NOEXCEPT { return iNanos / NANOS_PER_MICRO; }

    /// @brief  The interval in milliseconds, truncated towards zero.
    ETL_API_NOIGN    ETL_INL_CEXPR ETL_INT64 ToMilliseconds() const ETL_NOEXCEPT { return iNanos / NANOS_PER_MILLI; }

    /// @brief  The interval in seconds, truncated towards zero.
    ETL_API_NOIGN    ETL_INL_CEXPR ETL_INT64 ToSeconds()      const ETL_NOEXCEPT { return iNanos / NANOS_PER_SECOND; }

    /// @brief  The interval in minutes, truncated towards zero.
    ETL_API_NOIGN    ETL_INL_CEXPR ETL_INT64 ToMinutes()      const ETL_NOEXCEPT { return iNanos / NANOS_PER_MINUTE; }

    /// @brief  The interval in hours, truncated towards zero.
    ETL_API_NOIGN    ETL_INL_CEXPR ETL_INT64 ToHours()        const ETL_NOEXCEPT { return iNanos / NANOS_PER_HOUR; }

    /// @brief  The interval in days, truncated towards zero.
    ETL_API_NOIGN    ETL_INL_CEXPR ETL_INT64 ToDays()         const ETL_NOEXCEPT { return iNanos / NANOS_PER_DAY; }


    ///-------------------------------------------------------------------------
    ///  Comparison
    ///-------------------------------------------------------------------------


    /// @brief  Total order, derived from the only field.
    ETL_API_NOIGN    ETL_INL_CEXPR auto operator <=> ( const SDuration & ) const = default;

    /// @brief  Equality, derived from the only field.
    ETL_API_NOIGN    ETL_INL_CEXPR bool operator ==  ( const SDuration & ) const = default;
};
function

Nanoseconds

Ethereal::Time#
inline constexpr SDuration Nanoseconds( ETL_INT64 iValue ) noexcept

Builds an interval from nanoseconds.

function

Microseconds

Ethereal::Time#
inline constexpr SDuration Microseconds( ETL_INT64 iValue ) noexcept

Builds an interval from microseconds.

function

Milliseconds

Ethereal::Time#
inline constexpr SDuration Milliseconds( ETL_INT64 iValue ) noexcept

Builds an interval from milliseconds.

function

Seconds

Ethereal::Time#
inline constexpr SDuration Seconds( ETL_INT64 iValue ) noexcept

Builds an interval from seconds.

function

Minutes

Ethereal::Time#
inline constexpr SDuration Minutes( ETL_INT64 iValue ) noexcept

Builds an interval from minutes.

function

Hours

Ethereal::Time#
inline constexpr SDuration Hours( ETL_INT64 iValue ) noexcept

Builds an interval from hours.

function

Days

Ethereal::Time#
inline constexpr SDuration Days( ETL_INT64 iValue ) noexcept

Builds an interval from days.

operator

operator+

Ethereal::Time#
inline constexpr SDuration operator + ( SDuration Left, SDuration Right ) noexcept

Sum of two intervals.

operator

operator-

Ethereal::Time#
inline constexpr SDuration operator - ( SDuration Left, SDuration Right ) noexcept

Difference of two intervals.

operator

operator-

Ethereal::Time#
inline constexpr SDuration operator - ( SDuration Value ) noexcept

Negation of an interval.

The smallest value of the range has no negation. There the result wraps around and returns the value itself, which is what the computation in ETL_UINT64 produces. NegateChecked refuses that case.
operator

operator*

Ethereal::Time#
inline constexpr SDuration operator * ( SDuration Left, ETL_INT64 iFactor ) noexcept

An interval multiplied by a scalar.

operator

operator*

Ethereal::Time#
inline constexpr SDuration operator * ( ETL_INT64 iFactor, SDuration Right ) noexcept

A scalar multiplied by an interval.

operator

operator/

Ethereal::Time#
inline constexpr SDuration operator / ( SDuration Left, ETL_INT64 iDivisor ) noexcept

An interval divided by a scalar, truncating towards zero.

operator

operator/

Ethereal::Time#
inline constexpr ETL_INT64 operator / ( SDuration Left, SDuration Right ) noexcept

How many times one interval fits in the other, truncating towards zero.

operator

operator%

Ethereal::Time#
inline constexpr SDuration operator % ( SDuration Left, SDuration Right ) noexcept

What is left when dividing one interval by the other.

function

AddChecked

Ethereal::Time#
inline constexpr ETimeError AddChecked( SDuration Left, SDuration Right, SDuration & ResultOut ) noexcept

Adds two intervals, refusing overflow.

Left
Addend.
Right
Addend.
ResultOut
Receives the sum. Untouched on overflow.
ETimeError::eOk, or ETimeError::eOverflow.
Does not allocate. Thread safety: full.
function

SubChecked

Ethereal::Time#
inline constexpr ETimeError SubChecked( SDuration Left, SDuration Right, SDuration & ResultOut ) noexcept

Subtracts two intervals, refusing overflow.

Left
Minuend.
Right
Subtrahend.
ResultOut
Receives the difference. Untouched on overflow.
ETimeError::eOk, or ETimeError::eOverflow.
function

MulChecked

Ethereal::Time#
inline constexpr ETimeError MulChecked( SDuration Value, ETL_INT64 iFactor, SDuration & ResultOut ) noexcept

Multiplies an interval by a scalar, refusing overflow.

Value
The interval.
iFactor
The scalar.
ResultOut
Receives the product. Untouched on overflow.
ETimeError::eOk, or ETimeError::eOverflow.
function

DivChecked

Ethereal::Time#
inline constexpr ETimeError DivChecked( SDuration Value, ETL_INT64 iDivisor, SDuration & ResultOut ) noexcept

Divides an interval by a scalar, refusing a zero divisor and overflow.

Value
The interval.
iDivisor
The scalar.
ResultOut
Receives the quotient. Untouched on failure.
ETimeError::eOk, ETimeError::eInvalidArgument for a zero divisor, or ETimeError::eOverflow for the only pair that overflows.
function

NegateChecked

Ethereal::Time#
inline constexpr ETimeError NegateChecked( SDuration Value, SDuration & ResultOut ) noexcept

Negation of an interval, refusing overflow.

Value
The interval.
ResultOut
Receives the negation. Untouched on overflow.
ETimeError::eOk, or ETimeError::eOverflow for the most negative value.
function

FloorTo

Ethereal::Time#
inline constexpr SDuration FloorTo( SDuration Value, SDuration Unit ) noexcept

Largest multiple of Unit that does not go above Value.

Rounds towards minus infinity, not towards zero: an instant before the zero mark goes down, not up.

Value
The interval to round.
Unit
The unit. The caller guarantees it is positive.
The rounded interval.
function

CeilTo

Ethereal::Time#
inline constexpr SDuration CeilTo( SDuration Value, SDuration Unit ) noexcept

Smallest multiple of Unit that does not go below Value.

Value
The interval to round.
Unit
The unit. The caller guarantees it is positive.
The rounded interval.
function

RoundTo

Ethereal::Time#
inline constexpr SDuration RoundTo( SDuration Value, SDuration Unit ) noexcept

Multiple of Unit closest to Value.

A tie goes away from zero. That is the rule most people expect from "rounding", and the one that does not shift the mean of a symmetric series. The choice is documented because it is not the only possible one: rounding to the nearest even would also be defensible.

Value
The interval to round.
Unit
The unit. The caller guarantees it is positive.
The rounded interval.
function

Abs

Ethereal::Time#
inline constexpr SDuration Abs( SDuration Value ) noexcept

Absolute value of an interval.

The smallest value of the range has no negation: there the result wraps around and returns the value itself. NegateChecked refuses that case.
function

Min

Ethereal::Time#
inline constexpr SDuration Min( SDuration Left, SDuration Right ) noexcept

The smaller of two intervals.

function

Max

Ethereal::Time#
inline constexpr SDuration Max( SDuration Left, SDuration Right ) noexcept

The larger of two intervals.

operator

operator""_ns

Ethereal::Time::Literals#
inline constexpr SDuration operator""_ns( unsigned long long uValue ) noexcept

Nanoseconds literal.

operator

operator""_us

Ethereal::Time::Literals#
inline constexpr SDuration operator""_us( unsigned long long uValue ) noexcept

Microseconds literal.

operator

operator""_ms

Ethereal::Time::Literals#
inline constexpr SDuration operator""_ms( unsigned long long uValue ) noexcept

Milliseconds literal.

operator

operator""_s

Ethereal::Time::Literals#
inline constexpr SDuration operator""_s( unsigned long long uValue ) noexcept

Seconds literal.

operator

operator""_min

Ethereal::Time::Literals#
inline constexpr SDuration operator""_min( unsigned long long uValue ) noexcept

Minutes literal.

operator

operator""_h

Ethereal::Time::Literals#
inline constexpr SDuration operator""_h( unsigned long long uValue ) noexcept

Hours literal.

format.hpp

#include <ethereal/cpp/time/format.hpp>

Date formatting and parsing of the Time module: RFC 3339, RFC 7231 and the log timestamp.

The caller gives the space and nothing here allocates. From the spec: "Format writes into a caller-provided char span and returns the byte count. No allocation, no snprintf, no stream. Integer-to-decimal uses a two-digit lookup table."

'snprintf' is out because it interprets a format string at run time, character by character, and asks the locale for the decimal separator. For a date whose format is known at compile time that is a whole interpreter running for nothing. Measured, it costs a few hundred nanoseconds against a target of forty.

The two digit table removes the divisions. Writing '2026' with divisions takes four divisions and four remainders, with the table it takes two divisions and two copies of two bytes. Every field of a date (month, day, hour, minute, second) has exactly two digits, so the table serves them all.

The functions return how many bytes were needed, not how many fit. When the result does not fit they write nothing, so a small buffer never holds half a date that looks whole.

const

kMaxRfc3339

Ethereal::Time#
inline constexpr std::size_t kMaxRfc3339 = 48u;

The size an RFC 3339 with nanoseconds and offset never exceeds.

'-2026-09-23T14:30:59.123456789+01:00' is 36. The year can be longer, so there is slack. A buffer of this size on the stack is always enough.

const

kRfc7231Size

Ethereal::Time#
inline constexpr std::size_t kRfc7231Size = 29u;

The size of an HTTP date, which is fixed: 'Sun, 06 Nov 1994 08:49:37 GMT'.

enum

EPrecision

Ethereal::Time#
C++
enum class   EPrecision : ETL_UINT8
{
    /// @brief  No decimal part: '2026-09-23T14:30:59Z'.
    eSeconds = 0,

    /// @brief  Three places: '2026-09-23T14:30:59.123Z'. What almost everybody wants.
    eMillis,

    /// @brief  Six places (microseconds).
    eMicros,

    /// @brief  Nine places (nanoseconds).
    eNanos
};

How many decimal places of the second are written.

function

FormatRfc3339

Ethereal::Time#
ETimeError FormatRfc3339( const SCivilTime & Civil, EPrecision ePrecision, ETL_INT32 iOffsetMin, char * pDest, std::size_t uSize, std::size_t * pWritten ) noexcept;

Writes an RFC 3339 date from a civil date.

Civil
The date.
ePrecision
How many decimal places of the second.
iOffsetMin
The offset, in minutes. Zero writes 'Z'.
pDest
Where to write. Not null terminated.
uSize
How much space there is.
pWritten
Receives how many bytes were needed, even when they did not fit. May be null.
eBufferTooSmall when it does not fit, and in that case nothing was written.
function

FormatRfc3339

Ethereal::Time#
ETimeError FormatRfc3339( STimePoint When, EPrecision ePrecision, char * pDest, std::size_t uSize, std::size_t * pWritten ) noexcept;

Writes an RFC 3339 date in UTC from an instant.

When
The instant.
ePrecision
How many decimal places of the second.
pDest
Where to write. Not null terminated.
uSize
How much space there is.
pWritten
Receives how many bytes were needed. May be null.
eOk, or eBufferTooSmall when it does not fit.
function

FormatRfc7231

Ethereal::Time#
ETimeError FormatRfc7231( const SCivilTime & Civil, char * pDest, std::size_t uSize, std::size_t * pWritten ) noexcept;

Writes an HTTP date: 'Sun, 06 Nov 1994 08:49:37 GMT'.

This is the RFC 7231 format, and the Http module needs it in both directions. The day and month names are in English and fixed, as the standard says. They do not go through the locale, which is exactly why this exists here.

Civil
The date, in UTC.
pDest
Where to write. Not null terminated.
uSize
How much space there is.
pWritten
Receives how many bytes were needed. May be null.
eOk, eBufferTooSmall, or eInvalidArgument for a month out of range or a year without four digits.
const

kLogSize

Ethereal::Time#
inline constexpr std::size_t kLogSize = 18u;

The fixed size of a log timestamp: '09-23 14:30:59.123'.

function

FormatLog

Ethereal::Time#
ETimeError FormatLog( const SCivilTime & Civil, char * pDest, std::size_t uSize ) noexcept;

Writes a compact log timestamp. Always 18 bytes.

Civil
The date.
pDest
Where to write. Not null terminated.
uSize
How much space there is.
eOk, or eBufferTooSmall.
function

ParseRfc3339

Ethereal::Time#
ETimeError ParseRfc3339( const char * pText, std::size_t uSize, bool bLenient, SCivilTime * pOut, ETL_INT32 * pOffsetMin ) noexcept;

Parses an ISO 8601 / RFC 3339 date.

Strict by default, as the spec asks: the separator must be an upper case 'T', the fields must have the exact number of digits, and the offset must be present.

The lenient mode accepts what the real world has: a space instead of the 'T', lower case 't' and 'z', and a missing offset (which then means UTC). It is an explicit choice because accepting everything by default is how two parts of a system end up disagreeing on what a date means.

pText
The text.
uSize
Its length.
bLenient
Lenient mode, see above. false is what should be used.
pOut
Receives the date.
pOffsetMin
Receives the parsed offset, in minutes. May be null.
eOk, eInvalidArgument for a null pointer, or eParseFailed.
function

ParseRfc3339

Ethereal::Time#
ETimeError ParseRfc3339( const char * pText, std::size_t uSize, bool bLenient, STimePoint * pOut ) noexcept;

Parses an RFC 3339 date straight into an instant, already in UTC.

pText
The text.
uSize
Its length.
bLenient
Lenient mode.
pOut
Receives the instant.
eOk, or the error of the parse or of the conversion.
function

ParseRfc7231

Ethereal::Time#
ETimeError ParseRfc7231( const char * pText, std::size_t uSize, SCivilTime * pOut ) noexcept;

Parses an HTTP date.

Accepts the three formats RFC 7231 requires: the preferred one ('Sun, 06 Nov 1994 08:49:37 GMT'), the obsolete RFC 850 one ('Sunday, 06-Nov-94 08:49:37 GMT') and the 'asctime' one ('Sun Nov 6 08:49:37 1994'). Reading all three is mandatory, writing only the first is what the standard says.

pText
The text.
uSize
Its length.
pOut
Receives the date.
eOk, eInvalidArgument, or eParseFailed.

sleep.hpp

#include <ethereal/cpp/time/sleep.hpp>

Sleeping with a hybrid wait, in the Time module.

From the spec: "Hybrid wait: spin with ETL_PAUSE for sub-microsecond waits, then yield, then OS wait. Thresholds are compile-time tunable constants."

A single kind of wait is not enough:

  • An OS wait for 200 ns makes no sense. The call itself costs more than that, and the wake up has millisecond granularity in many configurations. Asking for 200 ns and waking 1 ms later is off by five thousand times.
  • A busy wait for 50 ms burns a whole core for 50 ms. On a laptop that is battery and fan, on a server it is a core another process did not get.

So there are three steps, and the limits between them are here instead of hidden: up to kSpinNanos busy wait with 'ETL_PAUSE' up to kYieldNanos yield to the scheduler above that OS wait, then fine tuning at the end

'timeBeginPeriod' is not called, by decision. From the spec: "On Windows use a high resolution waitable timer, and explicitly do not call 'timeBeginPeriod', which is a process-wide side effect and unacceptable in a library." It changes the timer of the whole process: a library that calls it makes the whole program, including code that never heard of it, wake more often, spend more battery and behave differently. Instead the module uses the high resolution waitable timer of Windows 10 1803 and later, which gives the same precision to this wait only. Older systems fall back to the normal timer and the worst case gets worse, measured in the README.

const

kSpinNanos

Ethereal::Time#
inline constexpr ETL_INT64 kSpinNanos = 2000;

Below this the wait is a busy wait, with 'ETL_PAUSE'.

const

kYieldNanos

Ethereal::Time#
inline constexpr ETL_INT64 kYieldNanos = 60000;
function

SleepFor

Ethereal::Time#
void SleepFor( SDuration Interval ) noexcept;
function

SleepUntil

Ethereal::Time#
void SleepUntil( STimePoint Target ) noexcept;

Sleeps until Target. The instant must come from the monotonic clock.

The monotonic clock on purpose: sleeping until an instant of the real time clock is sleeping until a time the system can change underneath. An NTP correction backwards would make the wait last hours longer.

Target
The instant to wake up at.
function

YieldThread

Ethereal::Time#
void YieldThread() noexcept;

Yields without sleeping. The middle step, exposed for those who want it alone.

stopwatch.hpp

#include <ethereal/cpp/time/stopwatch.hpp>
class

CStopwatch

Ethereal::Time#

Stopwatch: measures an interval, with pause and laps.

class CStopwatch final

Thirty two bytes, and it never allocates. Laps are not stored here: Lap returns the split and the caller decides where to put it. An overload writes into a span given by the caller, for those who want the list ready without writing the loop.

It stores raw counts in nanoseconds instead of STimePoint, because the clock tag would be the same in all three fields and cost bytes the size budget does not have. The clock is always the steady one: measuring an interval with the wall clock gives wrong numbers when the system sets the time.

Thread safety: none. Callers using it from more than one thread serialize.
constructor

CStopwatch

#
CStopwatch() noexcept = default;

Builds the stopwatch stopped and at zero.

function

Start

#
void Start() noexcept

Starts the stopwatch.

Calling it on a running stopwatch does nothing. Otherwise a repeated Start would lose the accumulated time and the measurement would shrink without anybody noticing.

function

Stop

#
void Stop() noexcept

Stops the stopwatch, keeping the time already run.

Calling it on a stopped stopwatch does nothing.

function

Reset

#
void Reset() noexcept

Resets the stopwatch to zero and leaves it stopped.

function

Restart

#
void Restart() noexcept

Resets the stopwatch to zero and starts it right away.

function

Elapsed

#
SDuration Elapsed() const noexcept

How much time has run, without stopping.

Reading while running is the common case: stopping to read would change what is being measured.

The accumulated time plus, when running, the split since the last Start.
function

IsRunning

#
bool IsRunning() const noexcept

Tells whether the stopwatch is running.

function

Lap

#
SDuration Lap() noexcept

Closes a lap and returns the split since the previous lap.

The first lap counts from Start. On a stopped stopwatch it returns zero, because there is no new split to close.

The split of the lap.
Does not allocate.
function

Lap

#
ETimeError Lap( std::span< SDuration > Laps, ETL_UINT32 & uCountInOut, SDuration & SplitOut ) noexcept

Closes a lap and appends it to the space given by the caller.

The stopwatch keeps no list of laps: the space belongs to the caller, so nothing here allocates. When the space runs out, the lap is still closed and the function reports that it did not fit.

Closing it even when it does not fit is deliberate: if the lap were not closed, its split would leak into the next one and every following number would be wrong because of a small buffer.

Laps
The space to append to.
uCountInOut
How many laps are already in the space. Goes up by one when the lap fits.
SplitOut
Receives the split of the lap. Always written.
ETimeError::eOk, or ETimeError::eBufferTooSmall when the space ran out.
Does not allocate.

tickscale.hpp

#include <ethereal/cpp/time/tickscale.hpp>

time.hpp

#include <ethereal/cpp/time/time.hpp>
function

GetTime

Ethereal::Time#
ETL_FLOAT GetTime( void ) noexcept;

Gets the time elapsed since the time system was initialized.

Returns the elapsed time in seconds, using the high resolution counters of each platform:

  • Windows: QueryPerformanceCounter
  • Linux: clock_gettime (CLOCK_MONOTONIC)
  • macOS: mach_absolute_time

The value returned is the time relative to the initialization of the internal instance of the time system. Suited to general measurements where performance comes first.

Elapsed time in seconds (millisecond precision). Returns -2.0f if the high performance counter is not available (Windows).
function

GetTimeWithPrecision

Ethereal::Time#
ETL_DOUBLE GetTimeWithPrecision( void ) noexcept;

Gets the time elapsed since the time system was initialized, with high precision.

Returns the elapsed time in seconds, using the high resolution counters of each platform:

  • Windows: QueryPerformanceCounter
  • Linux: clock_gettime (CLOCK_MONOTONIC)
  • macOS: mach_absolute_time

The extended precision version returns a double floating point value, suited to sensitive time calculations, profiling and high precision measurements.

Elapsed time in seconds (high precision). Returns -2.0 if the high performance counter is not available (Windows).

time_common.hpp

#include <ethereal/cpp/time/time_common.hpp>

Failure cause shared by the whole Time module.

Declares ETimeError and TimeErrorName. Every fallible operation of the module returns this enum and writes its result to an output parameter.

enum

ETimeError

Ethereal::Time#
C++
enum class   ETimeError : ETL_INT32
{
    /// @brief  The operation finished as requested.
    eOk = 0,

    /// @brief  The computation went out of the range of @c ETL_INT64 nanoseconds.
    ///
    /// @details  Only the checked variants return it. The normal operators do
    ///            not check on purpose, they are the hot path.
    eOverflow,

    /// @brief  An argument has no usable value (zero divisor, non positive
    ///          unit, calendar field out of range).
    eInvalidArgument,

    /// @brief  The space given by the caller does not fit the result.
    ///
    /// @details  The formatting functions never allocate, the caller gives the
    ///            space. When it is not enough, this is returned.
    eBufferTooSmall,

    /// @brief  The text does not match the requested format.
    eParseFailed,

    /// @brief  The platform does not offer the feature (clock, resolution or
    ///          counter).
    eUnsupported,

    /// @brief  The system call failed. The raw code goes out through a
    ///          parameter when the function offers one.
    eSystemError,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///          has ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed
};

Portable cause of failure of a time operation.

Narrow POD enum, in the same format as Ethereal::Network::ENetError and the other modules: eOk is zero, and the value travels in the return register while the result goes out through a parameter.

There is no generic result type in this library, and none is created here. Each module declares its own enum, and the conversion to the diagnostic model happens at the consumer.

function

TimeErrorName

Ethereal::Time#
const ETL_CHAR * TimeErrorName( ETimeError eError ) noexcept;

Readable name of an ETimeError, for logging and diagnostics.

eError
The cause to name.
Static null terminated string. Never null, not even for an unknown value.
Thread safety: full. Touches no state.

timer.hpp

#include <ethereal/cpp/time/timer.hpp>

Hierarchical timer wheel and the single timer of the Time module.

From the spec: "O(1) insert, O(1) cancel, O(1) amortized expiry. A priority queue is not acceptable here." A binary heap costs O(log n) per insertion, and with a million live timers that is twenty comparisons and twenty jumps per Arm. Worse, cancelling in a heap is O(n) unless the position of each element is stored and fixed on every swap, and a system with many timers cancels more than it expires (every network request that answers in time cancels its deadline).

The wheel has four levels of 256 slots and works like an odometer. Level 0 has 256 slots of 1 ms and covers 256 ms. When it wraps, it moves one slot of level 1, whose slots are worth 256 ms each, and so on: level 0: 1 ms per slot covers 256 ms level 1: 256 ms per slot covers 65.5 s level 2: 65.5 s per slot covers 4.66 h level 3: 4.66 h per slot covers 49.7 days

Inserting is finding the level (a leading zero count) and linking at the head of a list, constant time. Cancelling is unlinking from a doubly linked list, constant time and with no search. Expiring touches only the slots the clock went through. The cost is the cascade: when level 0 wraps, the timers of the next slot of level 1 are spread over level 0. Each timer goes down a level at most three times in its life, which gives the "amortized" of the spec.

The spec says "roughly 68 years at millisecond granularity", and that does not add up. Four levels of 256 slots at 1 ms give 256^4 ms, which is 49.7 days. The 68 years are what a 31 bit counter of seconds gives, which is another thing. The choice here was to follow the numbers and not the conclusion: four levels, 256 slots, 1 ms. A timer armed beyond 49.7 days is not refused. It stays in the last slot of the last level and is redistributed when the wheel gets there, which is what a hierarchical wheel does anyway. It costs one more cascade.

struct

STimerHandle

Ethereal::Time#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   STimerHandle   final
{
    /// @brief  Index of the entry in the wheel. 0xFFFFFFFF means no timer.
    ETL_UINT32    uIndex = 0xFFFFFFFFu;

    /// @brief  Generation of the entry when the handle was created.
    ETL_UINT32    uGeneration = 0u;


    /// @brief  Tells whether the handle points to an entry.
    ETL_API_NOIGN    bool IsValid() const ETL_NOEXCEPT    { return uIndex != 0xFFFFFFFFu; }

    /// @brief  The empty handle.
    ETL_API_NOIGN    static STimerHandle None() ETL_NOEXCEPT    { return STimerHandle{}; }
};

A timer handle. Cancelling goes through it, never through a scan.

The two fields together make cancelling safe: the index says where the timer is, and the generation says whether it is still the same one. A handle of a timer that already fired has an old generation, and cancelling it does nothing, instead of cancelling the timer that took that place in the meantime.

alias

void

Ethereal::Time#
using ETL_TimerFn = void ( * )( void * pCtx, STimerHandle H );
struct

STimerWheelParams

Ethereal::Time#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   STimerWheelParams   final
{
    /// @brief  Size of this struct, for version checking.
    ETL_UINT32        uStructSize = static_cast< ETL_UINT32 >( sizeof( STimerWheelParams ) );

    /// @brief  How many timers fit before the wheel grows.
    std::size_t        uInitialTimers = 1024u;

    /// @brief  How many milliseconds a level 0 slot is worth.
    ETL_UINT32        uMsPerSlot = 1u;
};

Parameters of CTimerWheel::Init.

struct

STimerWheelStats

Ethereal::Time#
C++
ETL_END_INTENDED_PADDING


/// @brief  Counters of a @ref CTimerWheel.
///
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   STimerWheelStats   final
{
    /// @brief  How many timers were armed.
    ETL_UINT64        uArmed = 0;

    /// @brief  How many timers were cancelled.
    ETL_UINT64        uCancelled = 0;

    /// @brief  How many timers fired.
    ETL_UINT64        uFired = 0;

    /// @brief  How many times a timer went down a level. This is the amortized cost.
    ETL_UINT64        uCascades = 0;

    /// @brief  How many are armed now.
    ETL_UINT64        uAlive = 0;

    /// @brief  How many slots were visited, in total.
    ETL_UINT64        uSlotsVisited = 0;
};
class

CTimerWheel

Ethereal::Time#
class CTimerWheel final
constructor

CTimerWheel

#
CTimerWheel() = default;

Builds an empty wheel. Call Init before use.

function

Init

#
ETimeError Init( const STimerWheelParams & Params ) noexcept;

Reserves what the wheel needs. All memory is requested here.

Params
The wheel parameters.
eOk, eInvalidArgument for a wrong struct size or a zero slot, or eNotLicensed.
function

Arm

#
STimerHandle Arm( SDuration Delay, ETL_TimerFn pFn, void * pCtx ) noexcept;

Arms a one shot timer.

Delay
How long from now. A zero or negative delay fires on the next Tick.
pFn
The callback.
pCtx
Passed to the callback.
The handle, or an invalid one when the wheel is not initialized or pFn is null.
function

ArmPeriodic

#
STimerHandle ArmPeriodic( SDuration Period, ETL_TimerFn pFn, void * pCtx ) noexcept;

Arms a periodic timer.

The period counts from the firing, not from when the callback was handled. A 10 ms timer whose callback takes 3 ms fires again 10 ms after the firing, not 13. Otherwise a periodic timer would drift by itself over time.

Period
The period.
pFn
The callback.
pCtx
Passed to the callback.
The handle, or an invalid one on failure.
function

Cancel

#
bool Cancel( STimerHandle H ) noexcept;

Cancels a timer. Constant time, with no search.

H
The handle.
true if it was really armed. false for an old handle, which is not an error: it is the right answer to "cancel that" when that already fired.
function

Rearm

#
bool Rearm( STimerHandle H, SDuration Delay ) noexcept;

Arms an existing timer again, with another delay.

H
The handle.
Delay
The new delay.
false for an old handle.
function

Remaining

#
SDuration Remaining( STimerHandle H ) const noexcept;

How long until the timer fires.

H
The handle.
The time left. Zero for an old handle.
function

IsArmed

#
bool IsArmed( STimerHandle H ) const noexcept;

Tells whether the handle points to an armed timer.

H
The handle.
true when armed and of the current generation.
function

Tick

#
std::size_t Tick( STimePoint Now ) noexcept;

Brings the wheel up to Now, firing whatever is on the way.

Now
The current instant. The first call only sets the base.
How many timers fired.
function

Advance

#
std::size_t Advance( SDuration Step ) noexcept;

Moves the wheel forward by Step, for callers without a clock.

Step
How much to move.
How many timers fired.
function

TimeToNext

#
SDuration TimeToNext() const noexcept;

How long until the next firing. Useful to sleep the right amount.

Returns a negative duration when nothing is armed. An event loop uses that to block with no deadline.

function

Count

#
std::size_t Count() const noexcept

How many timers are armed.

function

Stats

#
const STimerWheelStats & Stats() const noexcept

The wheel counters.

function

Clear

#
void Clear() noexcept;

Disarms every timer. Old handles stop being valid.

class

CTimer

Ethereal::Time#
class CTimer final
constructor

CTimer

#
CTimer() = default;

Builds a timer with no wheel.

constructor

CTimer

#
explicit CTimer( CTimerWheel * const pWheel ) noexcept : m_pWheel( pWheel )

Builds a timer attached to a wheel.

pWheel
The wheel.
function

Attach

#
void Attach( CTimerWheel * pWheel ) noexcept;

Disarms the timer and attaches it to another wheel.

pWheel
The wheel.
function

Arm

#
bool Arm( SDuration Delay, ETL_TimerFn pFn, void * pCtx ) noexcept;

Arms a one shot timer, disarming the previous one.

Delay
How long from now.
pFn
The callback.
pCtx
Passed to the callback.
true when armed.
function

ArmPeriodic

#
bool ArmPeriodic( SDuration Period, ETL_TimerFn pFn, void * pCtx ) noexcept;

Arms a periodic timer, disarming the previous one.

Period
The period.
pFn
The callback.
pCtx
Passed to the callback.
true when armed.
function

Rearm

#
bool Rearm( SDuration Delay ) noexcept;

Arms the timer again, with another delay.

Delay
The new delay.
false when there is no wheel or the timer is not armed.
function

Disarm

#
bool Disarm() noexcept;

Disarms the timer. Returns true if it was armed.

function

IsArmed

#
bool IsArmed() const noexcept;

Tells whether the timer is armed.

function

Remaining

#
SDuration Remaining() const noexcept;

How long until the timer fires. Zero when not armed.

function

Handle

#
STimerHandle Handle() const noexcept

The handle in the wheel.