Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: The most precise second (timer)

by GrandFather (Saint)
on Dec 03, 2019 at 03:58 UTC ( [id://11109577]=note: print w/replies, xml ) Need Help??


in reply to The most precise second (timer)

If the concern is first ensuring errors don't accumulate and second an emphasis on minimum variation in period then the following code should help:

use strict; use warnings; use Time::HiRes qw/time sleep/; my $nextTick = int (time()); while (1) { $nextTick += 1.0; # We want to stuff again in 1 second my $wait = 0.99 - ($nextTick - time()); # allow 10ms slop in sleep + period sleep $wait if $wait > 0.0; 1 while time() < $nextTick; # spin until time is up RunStuff(); } sub RunStuff { # kick off required sub tasks here print time(), "\n"; }

The key is to calculate when the next interesting epoch is, then sleep for most of the time until then. The 1 while ... loop is a busy wait until the next epoch time has arrived.

Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11109577]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2024-04-24 11:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found