gettimeofday on uLinux wierd behaviour
<p>Recently i've been trying to create a wait function that waits for 25 ms using the wall clock as reference. I looked around and found "gettimeofday", but i've been having problems with it. My code (simplified):</p>

<pre><code>while(1)
{
    timeval start, end;
    double t_us;
    bool release = false;    
    while (release == false)
    {
        gettimeofday(&amp;start, NULL);

        DoStuff();

        {
            gettimeofday(&amp;end, NULL);
            t_us = ( (end.tv_sec - start.tv_sec) * 1000*1000) + (end.tv_usec - start.tv_usec);

            if (t_us &gt;= 25000) //25 ms
            {
                release = true;
            }
        }
    }
}
</code></pre>

<p>This code runs in a thread (Posix) and, on it's its own, works fine. DoStuff() is called every 25ms. It does however eat all the CPU if it can (as you might expect) so obviously this isn't a good idea.</p>

<p>When I tried throttling it by adding a Sleep(1); in the wait loop after the if statement, the entire thing slows by about 50% (that is, it called DoStuff every 37ms or so. This makes no sense to me - assuming DoStuff and any other threads complete their tasks in under (25 - 1) ms the called rate of DoStuff shouldn't be affected (allowing a 1ms error margin)</p>

<p>I also tried Sleep(0), usleep(1000) and usleep(0) but the behaviour is the same.</p>

<p>The same behaviour occurs whenever another higher priority thread needs CPU time (without the sleep). It's as if the clock stops counting when the thread reliqnuishes runtime.</p>

<p>I'm aware that gettimeofday is vulnerable to things like NTP updates etc... so I tried using clock_gettime but linking -ltr on my system causes problems so i don't think that is an option.</p>

<p>Does anyone know what i'm doing wrong?</p>
