View source code
Display the source code in std/datetime/stopwatch.d from which this page was generated on github.
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 local clone.

Struct std.datetime.stopwatch.StopWatch

StopWatch is used to measure time just like one would do with a physical stopwatch, including stopping, restarting, and/or resetting it.

struct StopWatch ;

MonoTime is used to hold the time, and it uses the system's monotonic clock, which is high precision and never counts backwards (unlike the wall clock time, which can count backwards, which is why SysTime should not be used for timing).

Note that the precision of StopWatch differs from system to system. It is impossible for it to be the same for all systems, since the precision of the system clock and other system-dependent and situation-dependent factors (such as the overhead of a context switch between threads) varies from system to system and can affect StopWatch's accuracy.


this (autostart) Constructs a StopWatch. Whether it starts immediately depends on the AutoStart argument.


running[get] boolReturns whether this StopWatch is currently running.


peek () Peek at the amount of time that the StopWatch has been running.
reset () Resets the StopWatch.
setTimeElapsed (timeElapsed) Sets the total time which the StopWatch has been running (i.e. what peek returns).
start () Starts the StopWatch.
stop () Stops the StopWatch.


Measure a time in milliseconds, microseconds, or nanoseconds

auto sw = StopWatch(;
// ... Insert operations to be timed here ...

long msecs =!"msecs";
long usecs =!"usecs";
long nsecs =!"nsecs";

assert(usecs >= msecs * 1000);
assert(nsecs >= usecs * 1000);


import core.thread : Thread;

auto sw = StopWatch(AutoStart.yes);

Duration t1 = sw.peek();
Duration t2 = sw.peek();
assert(t2 > t1);


Duration t3 = sw.peek();
assert(t3 > t2);
Duration t4 = sw.peek();
writeln(t3); // t4


Duration t5 = sw.peek();
assert(t5 > t4);

// If stopping or resetting the StopWatch is not required, then
// MonoTime can easily be used by itself without StopWatch.
auto before = MonoTime.currTime;
// do stuff...
auto timeElapsed = MonoTime.currTime - before;


Jonathan M Davis and Kato Shoichi


Boost License 1.0.