title: Linux, timerfd accuracy
body: <p>I have a system that needs at least 10 mseconds of accuracy for timers.<br />
  I went for timerfd as it suits me perfectly, but found that even for times up to 15 milliseconds it is not accurate at all, either that or I don't understand how it works.</p>
  <p>The times I have measured were up to 21 mseconds on a 10 mseconds timer.<br />
  I have put together a quick test that shows my problem.<br />
  Here a test:</p>
  <pre><code>#include &lt;sys/timerfd.h&gt;
  #include &lt;time.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdint.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;inttypes.h&gt;
  
  int main(int argc, char *argv[]){
  
      int timerfd = timerfd_create(CLOCK_MONOTONIC,0);
      int milliseconds = atoi(argv[1]);
      struct itimerspec timspec;
      bzero(&amp;timspec, sizeof(timspec));
      timspec.it_interval.tv_sec = 0;
      timspec.it_interval.tv_nsec = milliseconds * 1000000;
      timspec.it_value.tv_sec = 0;
      timspec.it_value.tv_nsec = 1;
  
      int res = timerfd_settime(timerfd, 0, &amp;timspec, 0);
      if(res &lt; 0){
         perror(&quot;timerfd_settime:&quot;);
         return 1;
      }
      uint64_t expirations = 0;
      int iterations = 0;
      while( res = read(timerfd, &amp;expirations, sizeof(expirations))){
          if(res &lt; 0){ perror(&quot;read:&quot;); continue; }
          if(expirations &gt; 1){
              printf(&quot;%&quot; PRIu64 &quot; expirations, %d iterations\n&quot;, expirations, iterations);
              break;
          }
          iterations++;
      }
      return 0;
  }
  </code></pre>
  <p>And executed like this:</p>
  <pre><code>Zack ~$ for i in 2 4 8 10 15; do echo &quot;intervals of $i milliseconds&quot;; ./test $i;done
  intervals of 2 milliseconds
  2 expirations, 1 iterations
  intervals of 4 milliseconds
  2 expirations, 6381 iterations
  intervals of 8 milliseconds
  2 expirations, 21764 iterations
  intervals of 10 milliseconds
  2 expirations, 1089 iterations
  intervals of 15 milliseconds
  2 expirations, 3085 iterations
  </code></pre>
  <p>Even assuming some possible delays, 15 milliseconds delays sounds too much for me.</p>