Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

core.time

Module containing core time functionality, such as Duration (which represents a duration of time) or MonoTime (which represents a timestamp of the system's monotonic clock).
Various functions take a string (or strings) to represent a unit of time (e.g. convert!("days", "hours")(numDays)). The valid strings to use with such functions are "years", "months", "weeks", "days", "hours", "minutes", "seconds", "msecs" (milliseconds), "usecs" (microseconds), "hnsecs" (hecto-nanoseconds - i.e. 100 ns) or some subset thereof. There are a few functions that also allow "nsecs", but very little actually has precision greater than hnsecs.
Cheat Sheet
Symbol Description
    Types
Duration Represents a duration of time of weeks or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds).
TickDuration Represents a duration of time in system clock ticks, using the highest precision that the system provides.
MonoTime Represents a monotonic timestamp in system clock ticks, using the highest precision that the system provides.
FracSec Represents fractional seconds (portions of time smaller than a second).
    Functions
convert Generic way of converting between two time units.
dur Allows constructing a Duration from the given time units with the given length.
weeks days hours
minutes seconds msecs
usecs hnsecs nsecs
Convenience aliases for dur.
abs Returns the absolute value of a duration.
Conversions
From Duration From TickDuration From FracSec From units
To Duration - tickDuration.to!Duration() - dur!"msecs"(5) or 5.msecs()
To TickDuration duration.to!TickDuration() - - TickDuration.from!"msecs"(msecs)
To FracSec duration.fracSec - - FracSec.from!"msecs"(msecs)
To units duration.total!"days" tickDuration.msecs fracSec.msecs convert!("days", "msecs")(msecs)
Authors:
Jonathan M Davis and Kato Shoichi

Source core/time.d

enum ClockType: int;
What type of clock to use with MonoTime / MonoTimeImpl or std.datetime.Clock.currTime. They default to ClockType.normal, and most programs do not need to ever deal with the others.
The other ClockTypes are provided so that other clocks provided by the underlying C, system calls can be used with MonoTimeImpl or std.datetime.Clock.currTime without having to use the C API directly.
In the case of the monotonic time, MonoTimeImpl is templatized on ClockType, whereas with std.datetime.Clock.currTime, its a runtime argument, since in the case of the monotonic time, the type of the clock affects the resolution of a MonoTimeImpl object, whereas with std.datetime.SysTime, its resolution is always hecto-nanoseconds regardless of the source of the time.
ClockType.normal, ClockType.coarse, and ClockType.precise work with both Clock.currTime and MonoTimeImpl. ClockType.second only works with Clock.currTime. The others only work with MonoTimeImpl.
normal
Use the normal clock.
bootTime
Linux-Only
Uses CLOCK_BOOTTIME.
coarse
Use the coarse clock, not the normal one (e.g. on Linux, that would be CLOCK_REALTIME_COARSE instead of CLOCK_REALTIME for clock_gettime if a function is using the realtime clock). It's generally faster to get the time with the coarse clock than the normal clock, but it's less precise (e.g. 1 msec instead of 1 usec or 1 nsec). Howeover, it is guaranteed to still have sub-second precision (just not as high as with ClockType.normal).
On systems which do not support a coarser clock, MonoTimeImpl!(ClockType.coarse) will internally use the same clock as Monotime does, and Clock.currTime!(ClockType.coarse) will use the same clock as Clock.currTime. This is because the coarse clock is doing the same thing as the normal clock (just at lower precision), whereas some of the other clock types (e.g. ClockType.processCPUTime) mean something fundamentally different. So, treating those as ClockType.normal on systems where they weren't natively supported would give misleading results.
Most programs should not use the coarse clock, exactly because it's less precise, and most programs don't need to get the time often enough to care, but for those rare programs that need to get the time extremely frequently (e.g. hundreds of thousands of times a second) but don't care about high precision, the coarse clock might be appropriate.
Currently, only Linux and FreeBSD/DragonFlyBSD support a coarser clock, and on other platforms, it's treated as ClockType.normal.
precise
Uses a more precise clock than the normal one (which is already very precise), but it takes longer to get the time. Similarly to ClockType.coarse, if it's used on a system that does not support a more precise clock than the normal one, it's treated as equivalent to ClockType.normal.
Currently, only FreeBSD/DragonFlyBSD supports a more precise clock, where it uses CLOCK_MONOTONIC_PRECISE for the monotonic time and CLOCK_REALTIME_PRECISE for the wall clock time.
processCPUTime
Linux,Solaris-Only
Uses CLOCK_PROCESS_CPUTIME_ID.
raw
Linux-Only
Uses CLOCK_MONOTONIC_RAW.
second
Uses a clock that has a precision of one second (contrast to the coarse clock, which has sub-second precision like the normal clock does).
FreeBSD/DragonFlyBSD are the only systems which specifically have a clock set up for this (it has CLOCK_SECOND to use with clock_gettime which takes advantage of an in-kernel cached value), but on other systems, the fastest function available will be used, and the resulting SysTime will be rounded down to the second if the clock that was used gave the time at a more precise resolution. So, it's guaranteed that the time will be given at a precision of one second and it's likely the case that will be faster than ClockType.normal, since there tend to be several options on a system to get the time at low resolutions, and they tend to be faster than getting the time at high resolutions.
So, the primary difference between ClockType.coarse and ClockType.second is that ClockType.coarse sacrifices some precision in order to get speed but is still fairly precise, whereas ClockType.second tries to be as fast as possible at the expense of all sub-second precision.
threadCPUTime
Linux,Solaris-Only
Uses CLOCK_THREAD_CPUTIME_ID.
uptime
FreeBSD-Only
Uses CLOCK_UPTIME.
uptimeCoarse
FreeBSD-Only
Uses CLOCK_UPTIME_FAST.
uptimePrecise
FreeBSD-Only
Uses CLOCK_UPTIME_PRECISE.
struct Duration;
Represents a duration of time of weeks or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds).
It is used when representing a duration of time - such as how long to sleep with core.thread.Thread.sleep.
In std.datetime, it is also used as the result of various arithmetic operations on time points.
Use the dur function or one of its non-generic aliases to create Durations.
It's not possible to create a Duration of months or years, because the variable number of days in a month or year makes it impossible to convert between months or years and smaller units without a specific date. So, nothing uses Durations when dealing with months or years. Rather, functions specific to months and years are defined. For instance, std.datetime.Date has add!"years" and add!"months" for adding years and months rather than creating a Duration of years or months and adding that to a std.datetime.Date. But Duration is used when dealing with weeks or smaller.
Examples:
import std.datetime;

assert(dur!"days"(12) == dur!"hnsecs"(10_368_000_000_000L));
assert(dur!"hnsecs"(27) == dur!"hnsecs"(27));
assert(std.datetime.Date(2010, 9, 7) + dur!"days"(5) ==
       std.datetime.Date(2010, 9, 12));

assert(days(-12) == dur!"hnsecs"(-10_368_000_000_000L));
assert(hnsecs(-27) == dur!"hnsecs"(-27));
assert(std.datetime.Date(2010, 9, 7) - std.datetime.Date(2010, 10, 3) ==
       days(-26));
Examples:
import core.time;

// using the dur template
auto numDays = dur!"days"(12);

// using the days function
numDays = days(12);

// alternatively using UFCS syntax
numDays = 12.days;

auto myTime = 100.msecs + 20_000.usecs + 30_000.hnsecs;
assert(myTime == 123.msecs);
static pure nothrow @nogc @property @safe Duration zero();
A Duration of 0. It's shorter than doing something like dur!"seconds"(0) and more explicit than Duration.init.
static pure nothrow @nogc @property @safe Duration max();
Largest Duration possible.
static pure nothrow @nogc @property @safe Duration min();
Most negative Duration possible.
const pure nothrow @nogc @safe int opCmp(Duration rhs);
Compares this Duration with the given Duration.
Returns:
this < rhs < 0
this == rhs 0
this > rhs > 0
const nothrow @nogc Duration opBinary(string op, D)(D rhs)
if ((op == "+" || op == "-" || op == "%") && is(_Unqual!D == Duration) || (op == "+" || op == "-") && is(_Unqual!D == TickDuration));
Adds, subtracts or calculates the modulo of two durations.
The legal types of arithmetic for Duration using this operator are
Duration + Duration --> Duration
Duration - Duration --> Duration
Duration % Duration --> Duration
Duration + TickDuration --> Duration
Duration - TickDuration --> Duration
Parameters:
D rhs The duration to add to or subtract from this Duration.
const nothrow @nogc Duration opBinaryRight(string op, D)(D lhs)
if ((op == "+" || op == "-") && is(_Unqual!D == TickDuration));
Adds or subtracts two durations.
The legal types of arithmetic for Duration using this operator are
TickDuration + Duration --> Duration
TickDuration - Duration --> Duration
Parameters:
D lhs The TickDuration to add to this Duration or to subtract this Duration from.
nothrow @nogc ref Duration opOpAssign(string op, D)(in D rhs)
if ((op == "+" || op == "-" || op == "%") && is(_Unqual!D == Duration) || (op == "+" || op == "-") && is(_Unqual!D == TickDuration));
Adds, subtracts or calculates the modulo of two durations as well as assigning the result to this Duration.
The legal types of arithmetic for Duration using this operator are
Duration + Duration --> Duration
Duration - Duration --> Duration
Duration % Duration --> Duration
Duration + TickDuration --> Duration
Duration - TickDuration --> Duration
Parameters:
D rhs The duration to add to or subtract from this Duration.
const nothrow @nogc Duration opBinary(string op)(long value)
if (op == "*" || op == "/");
Multiplies or divides the duration by an integer value.
The legal types of arithmetic for Duration using this operator overload are
Duration * long --> Duration
Duration / long --> Duration
Parameters:
long value The value to multiply this Duration by.
nothrow @nogc ref Duration opOpAssign(string op)(long value)
if (op == "*" || op == "/");
Multiplies/Divides the duration by an integer value as well as assigning the result to this Duration.
The legal types of arithmetic for Duration using this operator overload are
Duration * long --> Duration
Duration / long --> Duration
Parameters:
long value The value to multiply/divide this Duration by.
const nothrow @nogc long opBinary(string op)(Duration rhs)
if (op == "/");
Divides two durations.
The legal types of arithmetic for Duration using this operator are
Duration / Duration --> long
Parameters:
Duration rhs The duration to divide this Duration by.
const nothrow @nogc Duration opBinaryRight(string op)(long value)
if (op == "*");
Multiplies an integral value and a Duration.
The legal types of arithmetic for Duration using this operator overload are
long * Duration --> Duration
Parameters:
long value The number of units to multiply this Duration by.
const nothrow @nogc Duration opUnary(string op)()
if (op == "-");
Returns the negation of this Duration.
const nothrow @nogc TickDuration opCast(T)()
if (is(_Unqual!T == TickDuration));
Returns a TickDuration with the same number of hnsecs as this Duration. Note that the conventional way to convert between Duration and TickDuration is using std.conv.to, e.g.: duration.to!TickDuration()
const nothrow @nogc bool opCast(T : bool)();
Allow Duration to be used as a boolean.
Returns:
true if this duration is non-zero.
template split(units...) if (allAreAcceptedUnits!("weeks", "days", "hours", "minutes", "seconds", "msecs", "usecs", "hnsecs", "nsecs")(units) && unitsAreInDescendingOrder(units))
Splits out the Duration into the given units.
split takes the list of time units to split out as template arguments. The time unit strings must be given in decreasing order. How it returns the values for those units depends on the overload used.
The overload which accepts function arguments takes integral types in the order that the time unit strings were given, and those integers are passed by ref. split assigns the values for the units to each corresponding integer. Any integral type may be used, but no attempt is made to prevent integer overflow, so don't use small integral types in circumstances where the values for those units aren't likely to fit in an integral type that small.
The overload with no arguments returns the values for the units in a struct with members whose names are the same as the given time unit strings. The members are all longs. This overload will also work with no time strings being given, in which case all of the time units from weeks through hnsecs will be provided (but no nsecs, since it would always be 0).
For both overloads, the entire value of the Duration is split among the units (rather than splitting the Duration across all units and then only providing the values for the requested units), so if only one unit is given, the result is equivalent to total.
"nsecs" is accepted by split, but "years" and "months" are not.
For negative durations, all of the split values will be negative.
Examples:
{
    auto d = dur!"days"(12) + dur!"minutes"(7) + dur!"usecs"(501223);
    long days;
    int seconds;
    short msecs;
    d.split!("days", "seconds", "msecs")(days, seconds, msecs);
    assert(days == 12);
    assert(seconds == 7 * 60);
    assert(msecs == 501);

    auto splitStruct = d.split!("days", "seconds", "msecs")();
    assert(splitStruct.days == 12);
    assert(splitStruct.seconds == 7 * 60);
    assert(splitStruct.msecs == 501);

    auto fullSplitStruct = d.split();
    assert(fullSplitStruct.weeks == 1);
    assert(fullSplitStruct.days == 5);
    assert(fullSplitStruct.hours == 0);
    assert(fullSplitStruct.minutes == 7);
    assert(fullSplitStruct.seconds == 0);
    assert(fullSplitStruct.msecs == 501);
    assert(fullSplitStruct.usecs == 223);
    assert(fullSplitStruct.hnsecs == 0);

    assert(d.split!"minutes"().minutes == d.total!"minutes");
}

{
    auto d = dur!"days"(12);
    assert(d.split!"weeks"().weeks == 1);
    assert(d.split!"days"().days == 12);

    assert(d.split().weeks == 1);
    assert(d.split().days == 5);
}

{
    auto d = dur!"days"(7) + dur!"hnsecs"(42);
    assert(d.split!("seconds", "nsecs")().nsecs == 4200);
}

{
    auto d = dur!"days"(-7) + dur!"hours"(-9);
    auto result = d.split!("days", "hours")();
    assert(result.days == -7);
    assert(result.hours == -9);
}
const nothrow @nogc void split(Args...)(out Args args)
if (units.length != 0 && (args.length == units.length) && allAreMutableIntegralTypes!Args);

const nothrow @nogc auto split();
Ditto
const nothrow @nogc @property long total(string units)()
if (units == "weeks" || units == "days" || units == "hours" || units == "minutes" || units == "seconds" || units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs");
Returns the total number of the given units in this Duration. So, unlike split, it does not strip out the larger units.
Examples:
assert(dur!"weeks"(12).total!"weeks" == 12);
assert(dur!"weeks"(12).total!"days" == 84);

assert(dur!"days"(13).total!"weeks" == 1);
assert(dur!"days"(13).total!"days" == 13);

assert(dur!"hours"(49).total!"days" == 2);
assert(dur!"hours"(49).total!"hours" == 49);

assert(dur!"nsecs"(2007).total!"hnsecs" == 20);
assert(dur!"nsecs"(2007).total!"nsecs" == 2000);
const pure nothrow @safe string toString();
Converts this Duration to a string.
The string is meant to be human readable, not machine parseable (e.g. whether there is an 's' on the end of the unit name usually depends on whether it's plural or not, and empty units are not included unless the Duration is zero). Any code needing a specific string format should use total or split to get the units needed to create the desired string format and create the string itself.
The format returned by toString may or may not change in the future.
Examples:
assert(Duration.zero.toString() == "0 hnsecs");
assert(weeks(5).toString() == "5 weeks");
assert(days(2).toString() == "2 days");
assert(hours(1).toString() == "1 hour");
assert(minutes(19).toString() == "19 minutes");
assert(seconds(42).toString() == "42 secs");
assert(msecs(42).toString() == "42 ms");
assert(usecs(27).toString() == "27 μs");
assert(hnsecs(5).toString() == "5 hnsecs");

assert(seconds(121).toString() == "2 minutes and 1 sec");
assert((minutes(5) + seconds(3) + usecs(4)).toString() ==
       "5 minutes, 3 secs, and 4 μs");

assert(seconds(-42).toString() == "-42 secs");
assert(usecs(-5239492).toString() == "-5 secs, -239 ms, and -492 μs");
const pure nothrow @nogc @property @safe bool isNegative();
Returns whether this Duration is negative.
pure nothrow @nogc @safe T to(string units, T, D)(D td)
if (is(_Unqual!D == TickDuration) && (units == "seconds" || units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs"));
Converts a TickDuration to the given units as either an integral value or a floating point value.
Parameters:
units The units to convert to. Accepts "seconds" and smaller only.
T The type to convert to (either an integral type or a floating point type).
D td The TickDuration to convert
Examples:
auto t = TickDuration.from!"seconds"(1000);

long tl = to!("seconds",long)(t);
assert(tl == 1000);

double td = to!("seconds",double)(t);
assert(_abs(td - 1000) < 0.001);
pure nothrow @nogc @safe Duration dur(string units)(long length)
if (units == "weeks" || units == "days" || units == "hours" || units == "minutes" || units == "seconds" || units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs");

alias weeks = dur!"weeks".dur;

alias days = dur!"days".dur;

alias hours = dur!"hours".dur;

alias minutes = dur!"minutes".dur;

alias seconds = dur!"seconds".dur;

alias msecs = dur!"msecs".dur;

alias usecs = dur!"usecs".dur;

alias hnsecs = dur!"hnsecs".dur;

alias nsecs = dur!"nsecs".dur;
These allow you to construct a Duration from the given time units with the given length.
You can either use the generic function dur and give it the units as a string or use the named aliases.
The possible values for units are "weeks", "days", "hours", "minutes", "seconds", "msecs" (milliseconds), "usecs", (microseconds), "hnsecs" (hecto-nanoseconds, i.e. 100 ns), and "nsecs".
Parameters:
units The time units of the Duration (e.g. "days").
long length The number of units in the Duration.
Examples:
// Generic
assert(dur!"weeks"(142).total!"weeks" == 142);
assert(dur!"days"(142).total!"days" == 142);
assert(dur!"hours"(142).total!"hours" == 142);
assert(dur!"minutes"(142).total!"minutes" == 142);
assert(dur!"seconds"(142).total!"seconds" == 142);
assert(dur!"msecs"(142).total!"msecs" == 142);
assert(dur!"usecs"(142).total!"usecs" == 142);
assert(dur!"hnsecs"(142).total!"hnsecs" == 142);
assert(dur!"nsecs"(142).total!"nsecs" == 100);

// Non-generic
assert(weeks(142).total!"weeks" == 142);
assert(days(142).total!"days" == 142);
assert(hours(142).total!"hours" == 142);
assert(minutes(142).total!"minutes" == 142);
assert(seconds(142).total!"seconds" == 142);
assert(msecs(142).total!"msecs" == 142);
assert(usecs(142).total!"usecs" == 142);
assert(hnsecs(142).total!"hnsecs" == 142);
assert(nsecs(142).total!"nsecs" == 100);
alias MonoTime = MonoTimeImpl!cast(ClockType)0.MonoTimeImpl;
alias for MonoTimeImpl instantiated with ClockType.normal. This is what most programs should use. It's also what much of MonoTimeImpl uses in its documentation (particularly in the examples), because that's what's going to be used in most code.
struct MonoTimeImpl(ClockType clockType);
Represents a timestamp of the system's monotonic clock.
A monotonic clock is one which always goes forward and never moves backwards, unlike the system's wall clock time (as represented by std.datetime.SysTime). The system's wall clock time can be adjusted by the user or by the system itself via services such as NTP, so it is unreliable to use the wall clock time for timing. Timers which use the wall clock time could easily end up never going off due to changes made to the wall clock time or otherwise waiting for a different period of time than that specified by the programmer. However, because the monotonic clock always increases at a fixed rate and is not affected by adjustments to the wall clock time, it is ideal for use with timers or anything which requires high precision timing.
So, MonoTime should be used for anything involving timers and timing, whereas std.datetime.SysTime should be used when the wall clock time is required.
The monotonic clock has no relation to wall clock time. Rather, it holds its time as the number of ticks of the clock which have occurred since the clock started (typically when the system booted up). So, to determine how much time has passed between two points in time, one monotonic time is subtracted from the other to determine the number of ticks which occurred between the two points of time, and those ticks are divided by the number of ticks that occur every second (as represented by MonoTime.ticksPerSecond) to get a meaningful duration of time. Normally, MonoTime does these calculations for the programmer, but the ticks and ticksPerSecond properties are provided for those who require direct access to the system ticks. The normal way that MonoTime would be used is
    MonoTime before = MonoTime.currTime;
    // do stuff...
    MonoTime after = MonoTime.currTime;
    Duration timeElapsed = after - before;
MonoTime is an alias to MonoTimeImpl!(ClockType.normal) and is what most programs should use for the monotonic clock, so that's what is used in most of MonoTimeImpl's documentation. But MonoTimeImpl can be instantiated with other clock types for those rare programs that need it.
See Also:
static nothrow @nogc @property @trusted MonoTimeImpl currTime();
The current time of the system's monotonic clock. This has no relation to the wall clock time, as the wall clock time can be adjusted (e.g. by NTP), whereas the monotonic clock always moves forward. The source of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other POSIX systems, clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock may indicate less time than has actually passed if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or Linux.
MonoTimeImpl zero();
A MonoTime of 0 ticks. It's provided to be consistent with Duration.zero, and it's more explicit than MonoTime.init.
MonoTimeImpl max();
Largest MonoTime possible.
MonoTimeImpl min();
Most negative MonoTime possible.
const pure nothrow @nogc int opCmp(MonoTimeImpl rhs);
Compares this MonoTime with the given MonoTime.
Returns:
this < rhs < 0
this == rhs 0
this > rhs > 0
const pure nothrow @nogc Duration opBinary(string op)(MonoTimeImpl rhs)
if (op == "-");
Subtracting two MonoTimes results in a Duration representing the amount of time which elapsed between them.
The primary way that programs should time how long something takes is to do
MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;

// How long it took.
Duration timeElapsed = after - before;
or to use a wrapper (such as a stop watch type) which does that.
Warning: Because Duration is in hnsecs, whereas MonoTime is in system ticks, it's usually the case that this assertion will fail
auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);
This is generally fine, and by its very nature, converting from system ticks to any type of seconds (hnsecs, nsecs, etc.) will introduce rounding errors, but if code needs to avoid any of the small rounding errors introduced by conversion, then it needs to use MonoTime's ticks property and keep all calculations in ticks rather than using Duration.
const pure nothrow @nogc MonoTimeImpl opBinary(string op)(Duration rhs)
if (op == "+" || op == "-");

pure nothrow @nogc ref MonoTimeImpl opOpAssign(string op)(Duration rhs)
if (op == "+" || op == "-");
Adding or subtracting a Duration to/from a MonoTime results in a MonoTime which is adjusted by that amount.
const pure nothrow @nogc @property long ticks();
The number of ticks in the monotonic time.
Most programs should not use this directly, but it's exposed for those few programs that need it.
The main reasons that a program might need to use ticks directly is if the system clock has higher precision than hnsecs, and the program needs that higher precision, or if the program needs to avoid the rounding errors caused by converting to hnsecs.
static pure nothrow @nogc @property long ticksPerSecond();
The number of ticks that MonoTime has per second - i.e. the resolution or frequency of the system's monotonic clock.
e.g. if the system clock had a resolution of microseconds, then ticksPerSecond would be 1_000_000.
const pure nothrow string toString();
pure nothrow @nogc @safe long convClockFreq(long ticks, long srcTicksPerSecond, long dstTicksPerSecond);
Converts the given time from one clock frequency/resolution to another.
See Also:
Examples:
// one tick is one second -> one tick is a hecto-nanosecond
assert(convClockFreq(45, 1, 10_000_000) == 450_000_000);

// one tick is one microsecond -> one tick is a millisecond
assert(convClockFreq(9029, 1_000_000, 1_000) == 9);

// one tick is 1/3_515_654 of a second -> 1/1_001_010 of a second
assert(convClockFreq(912_319, 3_515_654, 1_001_010) == 259_764);

// one tick is 1/MonoTime.ticksPerSecond -> one tick is a nanosecond
// Equivalent to ticksToNSecs
auto nsecs = convClockFreq(1982, MonoTime.ticksPerSecond, 1_000_000_000);
pure nothrow @nogc @safe long ticksToNSecs(long ticks);
Convenience wrapper around convClockFreq which converts ticks at a clock frequency of MonoTime.ticksPerSecond to nanoseconds.
It's primarily of use when MonoTime.ticksPerSecond is greater than hecto-nanosecond resolution, and an application needs a higher precision than hecto-nanoceconds.
See Also:
Examples:
auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto diffInTicks = after.ticks - before.ticks;
auto diffInNSecs = ticksToNSecs(diffInTicks);
assert(diffInNSecs == convClockFreq(diffInTicks, MonoTime.ticksPerSecond, 1_000_000_000));
pure nothrow @nogc @safe long nsecsToTicks(long ticks);
The reverse of ticksToNSecs.
struct TickDuration;
Warning: TickDuration will be deprecated in the near future (once all uses of it in Phobos have been deprecated). Please use MonoTime for the cases where a monotonic timestamp is needed and Duration when a duration is needed, rather than using TickDuration. It has been decided that TickDuration is too confusing (e.g. it conflates a monotonic timestamp and a duration in monotonic clock ticks) and that having multiple duration types is too awkward and confusing.
Represents a duration of time in system clock ticks.
The system clock ticks are the ticks of the system clock at the highest precision that the system provides.
static immutable long ticksPerSec;
The number of ticks that the system clock has in one second.
If ticksPerSec is 0, then then TickDuration failed to get the value of ticksPerSec on the current system, and TickDuration is not going to work. That would be highly abnormal though.
static immutable TickDuration appOrigin;
The tick of the system clock (as a TickDuration) when the application started.
static pure nothrow @nogc @property @safe TickDuration zero();
It's the same as TickDuration(0), but it's provided to be consistent with Duration and FracSec, which provide zero properties.
static pure nothrow @nogc @property @safe TickDuration max();
Largest TickDuration possible.
static pure nothrow @nogc @property @safe TickDuration min();
Most negative TickDuration possible.
long length;
The number of system ticks in this TickDuration.
You can convert this length into the number of seconds by dividing it by ticksPerSec (or using one the appropriate property function to do it).
const pure nothrow @nogc @property @safe long seconds();
Returns the total number of seconds in this TickDuration.
const pure nothrow @nogc @property @safe long msecs();
Returns the total number of milliseconds in this TickDuration.
const pure nothrow @nogc @property @safe long usecs();
Returns the total number of microseconds in this TickDuration.
const pure nothrow @nogc @property @safe long hnsecs();
Returns the total number of hecto-nanoseconds in this TickDuration.
const pure nothrow @nogc @property @safe long nsecs();
Returns the total number of nanoseconds in this TickDuration.
pure nothrow @nogc @safe TickDuration from(string units)(long length)
if (units == "seconds" || units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs");
This allows you to construct a TickDuration from the given time units with the given length.
Parameters:
units The time units of the TickDuration (e.g. "msecs").
long length The number of units in the TickDuration.
const pure nothrow @nogc @safe Duration opCast(T)()
if (is(_Unqual!T == Duration));
Returns a Duration with the same number of hnsecs as this TickDuration. Note that the conventional way to convert between TickDuration and Duration is using std.conv.to, e.g.: tickDuration.to!Duration()
pure nothrow @nogc ref @safe TickDuration opOpAssign(string op)(TickDuration rhs)
if (op == "+" || op == "-");
Adds or subtracts two TickDurations as well as assigning the result to this TickDuration.
The legal types of arithmetic for TickDuration using this operator are
TickDuration += TickDuration --> TickDuration
TickDuration -= TickDuration --> TickDuration
Parameters:
TickDuration rhs The TickDuration to add to or subtract from this TickDuration.
const pure nothrow @nogc @safe TickDuration opBinary(string op)(TickDuration rhs)
if (op == "+" || op == "-");
Adds or subtracts two TickDurations.
The legal types of arithmetic for TickDuration using this operator are
TickDuration + TickDuration --> TickDuration
TickDuration - TickDuration --> TickDuration
Parameters:
TickDuration rhs The TickDuration to add to or subtract from this TickDuration.
const pure nothrow @nogc @safe TickDuration opUnary(string op)()
if (op == "-");
Returns the negation of this TickDuration.
const pure nothrow @nogc @safe int opCmp(TickDuration rhs);
operator overloading "<, >, <=, >="
pure nothrow @nogc @safe void opOpAssign(string op, T)(T value)
if (op == "*" && (__traits(isIntegral, T) || __traits(isFloating, T)));
The legal types of arithmetic for TickDuration using this operator overload are
TickDuration * long --> TickDuration
TickDuration * floating point --> TickDuration
Parameters:
T value The value to divide from this duration.
pure @safe void opOpAssign(string op, T)(T value)
if (op == "/" && (__traits(isIntegral, T) || __traits(isFloating, T)));
The legal types of arithmetic for TickDuration using this operator overload are
TickDuration / long --> TickDuration
TickDuration / floating point --> TickDuration
Parameters:
T value The value to divide from this TickDuration.
Throws:
TimeException if an attempt to divide by 0 is made.
const pure nothrow @nogc @safe TickDuration opBinary(string op, T)(T value)
if (op == "*" && (__traits(isIntegral, T) || __traits(isFloating, T)));
The legal types of arithmetic for TickDuration using this operator overload are
TickDuration * long --> TickDuration
TickDuration * floating point --> TickDuration
Parameters:
T value The value to divide from this TickDuration.
const pure @safe TickDuration opBinary(string op, T)(T value)
if (op == "/" && (__traits(isIntegral, T) || __traits(isFloating, T)));
The legal types of arithmetic for TickDuration using this operator overload are
TickDuration / long --> TickDuration
TickDuration / floating point --> TickDuration
Parameters:
T value The value to divide from this TickDuration.
Throws:
TimeException if an attempt to divide by 0 is made.
pure nothrow @nogc @safe this(long ticks);
Parameters:
long ticks The number of ticks in the TickDuration.
static nothrow @nogc @property @trusted TickDuration currSystemTick();
The current system tick. The number of ticks per second varies from system to system. currSystemTick uses a monotonic clock, so it's intended for precision timing by comparing relative time values, not for getting the current system time.
On Windows, QueryPerformanceCounter is used. On Mac OS X, mach_absolute_time is used, while on other Posix systems, clock_gettime is used. If mach_absolute_time or clock_gettime is unavailable, then Posix systems use gettimeofday (the decision is made when TickDuration is compiled), which unfortunately, is not monotonic, but if mach_absolute_time and clock_gettime aren't available, then gettimeofday is the the best that there is.
Warning: On some systems, the monotonic clock may stop counting when the computer goes to sleep or hibernates. So, the monotonic clock could be off if that occurs. This is known to happen on Mac OS X. It has not been tested whether it occurs on either Windows or on Linux.
Throws:
TimeException if it fails to get the time.
pure nothrow @nogc @safe long convert(string from, string to)(long value)
if ((from == "weeks" || from == "days" || from == "hours" || from == "minutes" || from == "seconds" || from == "msecs" || from == "usecs" || from == "hnsecs" || from == "nsecs") && (to == "weeks" || to == "days" || to == "hours" || to == "minutes" || to == "seconds" || to == "msecs" || to == "usecs" || to == "hnsecs" || to == "nsecs") || (from == "years" || from == "months") && (to == "years" || to == "months"));
Generic way of converting between two time units. Conversions to smaller units use truncating division. Years and months can be converted to each other, small units can be converted to each other, but years and months cannot be converted to or from smaller units (due to the varying number of days in a month or year).
Parameters:
from The units of time to convert from.
to The units of time to convert to.
long value The value to convert.
Examples:
assert(convert!("years", "months")(1) == 12);
assert(convert!("months", "years")(12) == 1);

assert(convert!("weeks", "days")(1) == 7);
assert(convert!("hours", "seconds")(1) == 3600);
assert(convert!("seconds", "days")(1) == 0);
assert(convert!("seconds", "days")(86_400) == 1);

assert(convert!("nsecs", "nsecs")(1) == 1);
assert(convert!("nsecs", "hnsecs")(1) == 0);
assert(convert!("hnsecs", "nsecs")(1) == 100);
assert(convert!("nsecs", "seconds")(1) == 0);
assert(convert!("seconds", "nsecs")(1) == 1_000_000_000);
struct FracSec;
Everything in druntime and Phobos that was using FracSec now uses Duration for greater simplicity. So, FracSec has been deprecated. It will be removed from the docs in October 2018, and removed completely from druntime in October 2019.
Represents fractional seconds.
This is the portion of the time which is smaller than a second and it cannot hold values which would be greater than or equal to a second (or less than or equal to a negative second).
It holds hnsecs internally, but you can create it using either milliseconds, microseconds, or hnsecs. What it does is allow for a simple way to set or adjust the fractional seconds portion of a Duration or a std.datetime.SysTime without having to worry about whether you're dealing with milliseconds, microseconds, or hnsecs.
FracSec's functions which take time unit strings do accept "nsecs", but because the resolution of Duration and std.datetime.SysTime is hnsecs, you don't actually get precision higher than hnsecs. "nsecs" is accepted merely for convenience. Any values given as nsecs will be converted to hnsecs using convert (which uses truncating division when converting to smaller units).
static pure nothrow @nogc @property @safe FracSec zero();
A FracSec of 0. It's shorter than doing something like FracSec.from!"msecs"(0) and more explicit than FracSec.init.
FracSec from(string units)(long value)
if (units == "msecs" || units == "usecs" || units == "hnsecs" || units == "nsecs");
Create a FracSec from the given units ("msecs", "usecs", or "hnsecs").
Parameters:
units The units to create a FracSec from.
long value The number of the given units passed the second.
Throws:
TimeException if the given value would result in a FracSec greater than or equal to 1 second or less than or equal to -1 seconds.
const nothrow @nogc FracSec opUnary(string op)()
if (op == "-");
Returns the negation of this FracSec.
const pure nothrow @nogc @property @safe int msecs();
The value of this FracSec as milliseconds.
pure @property @safe void msecs(int milliseconds);
The value of this FracSec as milliseconds.
Parameters:
int milliseconds The number of milliseconds passed the second.
Throws:
TimeException if the given value is not less than 1 second and greater than a -1 seconds.
const pure nothrow @nogc @property @safe int usecs();
The value of this FracSec as microseconds.
pure @property @safe void usecs(int microseconds);
The value of this FracSec as microseconds.
Parameters:
int microseconds The number of microseconds passed the second.
Throws:
TimeException if the given value is not less than 1 second and greater than a -1 seconds.
const pure nothrow @nogc @property @safe int hnsecs();
The value of this FracSec as hnsecs.
pure @property @safe void hnsecs(int hnsecs);
The value of this FracSec as hnsecs.
Parameters:
int hnsecs The number of hnsecs passed the second.
Throws:
TimeException if the given value is not less than 1 second and greater than a -1 seconds.
const pure nothrow @nogc @property @safe int nsecs();
The value of this FracSec as nsecs.
Note that this does not give you any greater precision than getting the value of this FracSec as hnsecs.
pure @property @safe void nsecs(long nsecs);
The value of this FracSec as nsecs.
Note that this does not give you any greater precision than setting the value of this FracSec as hnsecs.
Parameters:
long nsecs The number of nsecs passed the second.
Throws:
TimeException if the given value is not less than 1 second and greater than a -1 seconds.
const pure nothrow @safe string toString();
Converts this TickDuration to a string.
class TimeException: object.Exception;
Exception type used by core.time.
pure nothrow @safe this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null);
Parameters:
string msg The message for the exception.
string file The file where the exception occurred.
size_t line The line number where the exception occurred.
Throwable next The previous exception in the chain of exceptions, if any.
pure nothrow @safe this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__);
Parameters:
string msg The message for the exception.
Throwable next The previous exception in the chain of exceptions.
string file The file where the exception occurred.
size_t line The line number where the exception occurred.
pure nothrow @nogc @safe Duration abs(Duration duration);

pure nothrow @nogc @safe TickDuration abs(TickDuration duration);
Returns the absolute value of a duration.