Is this a good way of setting up a timer?

Jonathan M Davis jmdavisProg at gmx.com
Fri Jun 3 14:32:34 PDT 2011


On 2011-06-03 14:22, Andrej Mitrovic wrote:
> I can't find any timers in phobos, basically I want some loop to run for a
> predetermined amount of time. Currently I use this:
> 
> import core.time;
> import std.datetime;
> import core.thread;
> 
> void main()
> {
> auto finalTime = Clock.currTime + dur!"seconds"(4);
> 
> while (true)
> {
> Thread.sleep(dur!("seconds")(1));
> if (Clock.currTime > finalTime)
> break;
> }
> }
> 
> Is that check doing any conversions in the background, or am I safe
> (performance-wise)? Well I'm probably wasting performance on waking up the
> thread every second.. hmm.

Generally, you'd just put it to sleep for the period of time that you want to 
wait for. The only reason that I see to keep waking it up is if it could be 
interrupted and effectively told to wake up - in which case you would be 
sleeping and waking up over and over again, checking to see if enough time had 
passed or if you had been signaled to stop waiting.

Now, if what you're trying to do is run the code in the loop for a 
predetermined length of time, then you'd just check the time every X 
iterations of the loop. If the loop is short, then X would be larger (to avoid 
asking for the time needlessly often and wasting cycles), whereas if the loop 
is long enough, then X might even be 1.

As your code stands though, I'm not sure what you're really trying to. Oh, and 
by the way, std.datetime publicly imports core.time, so if you import 
std.datetime, you don't need to import core.time.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list