alternate approach to timer inaccuracy due to cached times

Marc Lehmann schmorp at
Sun Oct 16 12:32:18 CEST 2011

On Sat, Oct 15, 2011 at 08:53:56AM -0500, Brandon Black <blblack at> wrote:
> > the timer has got an event but the IO hasn't yet.
> Priorities should still fix things, within the limitation that they
> can't make the timer fire "on time" if the loop iteration is taking

consider the following timeline:

    0ms data arrives
      ^ event loop detects I/O event
  700ms more data arrives
  900ms all data (the 0ms and 700ms arrival data) is read
      ^ start timeout for 500ms
 1000ms next event loop iteration
      ^ timeout expires even though data has been received 300ms ago

The priority does not help you with the later data that has arrived, but is
read. The problem is that the timestamp we get refers to the original data
received, while the later data has no accurate timestamp because the event
loop basically defines your accuracy.

But the solutions still stay the same:

- if you know your event loop regularly only has 1s resolution, you need
  to take this into account for timeouts.
- if its a rare event, but expected, use ev_now_update
- if that is not possible, take a timestamp with ev_time, then
  you have two times, the time data was first detected and a 
  later time where you might have received more data.
- using a list and starting the timers in ev_prepare can reduce
  overhead at the cost of even more accuracy.

It should be obvious that a 500ms timeout is simply nonsensical for the
above timeline, unless the delay event is really rare.

When libev uses gettimeofday, you often don't even have a syscall overhead
for ev_time, though, so timestamping before creating a timer might well be
an option.

The overhead for a real syscall might even go down in the noise anyway,
if depending on how many reads you do. To my knowledge, nobody ever
complained that libevent calls gettimeofday for every timer, and that
library is supposed to play in the same league as libev.

                The choice of a       Deliantra, the free code+content MORPG
      -----==-     _GNU_    
      ----==-- _       generation
      ---==---(_)__  __ ____  __      Marc Lehmann
      --==---/ / _ \/ // /\ \/ /      schmorp at
      -=====/_/_//_/\_,_/ /_/\_\

More information about the libev mailing list