Note that there are some explanatory texts on larger screens.

plurals
  1. POtime delay in C. usleep
    text
    copied!<p>I'm developing the game server, which is written on C. And I need to develop a cycle with a certain frequency (50 times per second) to perform an algorithm. The problem is that I can't pause the program for an exact time interval - 20000 microseconds. Function <code>usleep(20000)</code> runs about 30000 microseconds. The result is always more on 10000 microseconds than expected.</p> <p>Here is my simple example of code:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;unistd.h&gt; int main( int argc, char ** argv ) { const unsigned long long nano = 1000000000; unsigned long long t1, t2; struct timespec tm; for(;;) { clock_gettime( CLOCK_REALTIME, &amp;tm ); t1 = tm.tv_nsec + tm.tv_sec * nano; usleep( 20000 ); clock_gettime( CLOCK_REALTIME, &amp;tm ); t2 = tm.tv_nsec + tm.tv_sec * nano; printf( "delay: %ld\n", ( t2 - t1 ) / 1000 ); } return 0; } </code></pre> <p>And the result of it's running:</p> <pre><code>$ ./a.out delay: 29233 delay: 29575 delay: 29621 delay: 29694 delay: 29688 delay: 29732 delay: 29709 delay: 29706 delay: 29666 delay: 29702 delay: 29702 delay: 29705 delay: 29789 delay: 29619 delay: 29785 delay: 29634 delay: 29692 delay: 29708 delay: 29701 delay: 29703 </code></pre> <p>I also tried to use function <code>select()</code>, but result is the same as with the <code>sleep()</code>.</p> <p>Explain to me, please, what's wrong with my code.</p> <p>p.s.:</p> <pre><code>$ uname -a FreeBSD home.com 9.0-RELEASE FreeBSD 9.0-RELEASE #0: Tue Jan 3 07:46:30 UTC 2012 root@farrell.cse.buffalo.edu:/usr/obj/usr/src/sys/GENERIC amd64 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload