Constructs a StopWatch. Whether it starts immediately depends on the AutoStart argument.
Peek at the amount of time that the StopWatch has been running.
Resets the StopWatch.
Sets the total time which the StopWatch has been running (i.e. what peek returns).
Starts the StopWatch.
Stops the StopWatch.
Returns whether this StopWatch is currently running.
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);
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(); assert(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;
StopWatch is used to measure time just like one would do with a physical stopwatch, including stopping, restarting, and/or resetting it.
core.time.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 std.datetime.systime.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.