04-23-07 12:19 PM
Maxim Yegorushkin <maxim.yegorushkin@gmail.com> writes:
> On 23 Apr, 06:02, Madhur <madhurr...@gmail.com> wrote:
>
> If what you are asking is a data structure to store your timers (time
> to expiry and the callback) you could use a standard ordered container
> (such as std::set or std::map), or a heap. This way adding or removing
> a timer would take O(lg2(N)).
>
> http://en.wikipedia.org/wiki/Heap_%28data_structure%29
More precisely, the (abstract) data structure needed here is called 'a
priority queue' (a thing items can be inserted into and they will be
returned from it in some defined order based on 'some sort
criterion'). A heap (binary tree with the property that a relation '>'
is defined on its elements and that node > child_of_node is always
true) is a fairly easy way to implement such a priority queue
efficiently.
There is a different method to implement timers, though, which is
'traditionally' used (or was traditionally used) in UNIX(*) kernels
and that is called 'a timing wheel'. This is a fixed size array used
as a ring buffer where new timers are linked onto a list at position
(current_front_element + delay_until_expiry) % array_size. This is a
hashing algorithm and it has the property that insertions and
deletions are O(1) if the lists themselves are unsorted. Finding a
timer that has expired is O(n). But it is even easier to implement.
[ Post a follow-up to this message ]
|