Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
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 learning in the Monastery: (2)
As of 2025-12-10 06:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (90 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.