View source code Display the source code in std/datetime.d from which this page was generated on github. 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. Page wiki View or edit the community-maintained wiki page associated with this page.

Struct std.datetime.StopWatch

StopWatch measures time as precisely as possible.

This class uses a high-performance counter. On Windows systems, it uses QueryPerformanceCounter, and on Posix systems, it uses clock_gettime if available, and gettimeofday otherwise.

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

Constructors

Name Description
this Auto start with constructor.

Properties

Name Type Description
running [get] bool Confirm whether this stopwatch is measuring time.

Methods

Name Description
opEquals
peek Peek at the amount of time which has passed since the stop watch was started.
reset Resets the stop watch.
setMeasured Set the amount of time which has been measured since the stop watch was started.
start Starts the stop watch.
stop Stops the stop watch.

Examples

void foo()
{
    StopWatch sw;
    enum n = 100;
    TickDuration[n] times;
    TickDuration last = TickDuration.from!"seconds"(0);
    foreach(i; 0..n)
    {
       sw.start(); //start/resume mesuring.
       foreach(unused; 0..1_000_000)
           bar();
       sw.stop();  //stop/pause measuring.
       //Return value of peek() after having stopped are the always same.
       writeln((i + 1) * 1_000_000, " times done, lap time: ",
               sw.peek().msecs, "[ms]");
       times[i] = sw.peek() - last;
       last = sw.peek();
    }
    real sum = 0;
    // To know the number of seconds,
    // use properties of TickDuration.
    // (seconds, msecs, usecs, hnsecs)
    foreach(t; times)
       sum += t.hnsecs;
    writeln("Average time: ", sum/n, " hnsecs");
}

Authors

Jonathan M Davis and Kato Shoichi

License

Boost License 1.0.

Comments