Better than "Clock.currStdTime()/10000000"
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Feb 15 07:58:41 PST 2017
On Wednesday, February 15, 2017 16:27:34 drug via Digitalmars-d-learn wrote:
> 15.02.2017 16:19, berni пишет:
> > I need to measure time elapsed in seconds, like this:
> >> auto start = Clock.currStdTime();
> >> // some stuff
> >> auto stop = Clock.currStdTime();
> >> auto duration = (stop-start)/10000000;
> >
> > This works, but I wonder if there is something better that using the
> > magic constant 10000000. I read about 10.secs giving the duration of 10
> > seconds, but I don't understand how to adapt this to my case. I've read
> > the documentation of core.time, std.datetime (and the Introduction to
> > this package) but I can't make head or tail of it.
> >
> > PS: It's not about benchmarking. I'd like to show the user the time
> > elapsed.
>
> doesn't it work for you?
> ```
> void main()
> {
> import std.datetime, core.thread, std.stdio;
>
> MonoTime before = MonoTime.currTime;
> Thread.sleep(dur!"msecs"(1000));
> MonoTime after = MonoTime.currTime;
> Duration timeElapsed = after - before;
>
> writeln(timeElapsed);
> }
> ```
> I get: "1 sec, 26 μs, and 4 hnsecs"
This is the correct way to do it. Using SysTime for timing things is wrong,
because it's not a monotonic clock. So, it could be changed - even going
backwards - while you're doing the timing. MonoTime, on the other hand, uses
the system's monotonic clock and is therefore guaranteed to move forward at
a fixed rate.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list