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
Name | Description |
---|---|
this
(autostart)
|
Constructs a StopWatch. Whether it starts immediately depends on the
AutoStart argument.
|
Properties
Name | Type | Description |
---|---|---|
running [get]
|
bool | Returns whether this StopWatch is currently running. |
Methods
Name | Description |
---|---|
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);
Running...
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;
Running...
Authors
Jonathan M Davis and Kato Shoichi