What I want to do is trigger the measurement cycle every X seconds regardless of how long (less than X, obviously) the measurement process takes.

That's why I used a while loop sleeping for 1 second each time to accumulate the 10 seconds, rather than a 10 second sleep:

my $deadline = time() + 10; while( 1 ) { sleep 1 while time() < $deadline; $deadline = time() +10; ## Do the something }
This way, no matter how long "Do something" takes, so long as it's less that 10 seconds, the next reading will be initiated on time. To within one second.

Eg. If it takes 3 seconds to process, the while loop will iterate 7 times. If it takes 7 seconds, the loop will iterate 3 times only.

If you need to get more accurate, then use Time::HiRes and sleep for 1/10 of a second in the while loop. It will be 10 times more accurate and still consume almost imeasurable cpu.

Need more accurate still? Then sleep for 1/100th of a second. It will still consume very little cpu and be another order of magnitude more accurate.

Beyond that, you start getting into the realms of how long it takes to read the clock, affecting your accuracy, but if you need accuracy beyond 1/1000th of a second, you should probably be using C or assembler.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

In reply to Re^3: Waiting for Alarm by BrowserUk
in thread Waiting for Alarm by n8ur

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.