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.

Constructors

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

Properties

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

Methods

NameDescription
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.

Example

Measure a time in milliseconds, microseconds, or nanoseconds

auto sw = StopWatch(AutoStart.no);
sw.start();
// ... Insert operations to be timed here ...
sw.stop();

long msecs = sw.peek.total!"msecs";
long usecs = sw.peek.total!"usecs";
long nsecs = sw.peek.total!"nsecs";

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

Example

import core.thread : Thread;

auto sw = StopWatch(AutoStart.yes);

Duration t1 = sw.peek();
Thread.sleep(usecs(1));
Duration t2 = sw.peek();
assert(t2 > t1);

Thread.sleep(usecs(1));
sw.stop();

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

sw.start();
Thread.sleep(usecs(1));

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;

Authors

Jonathan M Davis and Kato Shoichi

License

Boost License 1.0.