3 ms·
That's O(N^2). Each time a timer expires, the code linearly scans the table for the next timer. You can do a lot better than that. The really good solution,
by Animats 10y ago
That's O(N^2). Each time a timer expires, the code linearly scans the table for the next timer. You can do a lot better than that. The really good solution, O(log N) with an upper bound, was developed in 1987.[1] The better algorithms all involve tree structures, as you'd expect.
[1] https://en.wikipedia.org/wiki/Order-maintenance_problem https://en.wikipedia.org/wiki/Order-maintenance_problem
[2] http://www.cs.cmu.edu/~sleator/papers/maintaining-order.pdf http://www.cs.cmu.edu/~sleator/papers/maintaining-order.pdf
- millstone 10y agoDumb question - why is just a heap not sufficient? You can efficiently remove from a heap by having each element track its index.
- optimiz3 10y agoPedantic people will argue that a heap is a technically tree - but you're right when it comes to the actual implementation.
- wahern 10y agoTimers have unique properties which permit more optimal solutions. A hierarchical timing wheel is O(1) to start, O(1) to cancel, and O(1) to expire. Finding the next minimum timer isn't O(1), but you don't actually need to know that information to process the timing wheels. It's O(1) to figure out the next _set_ of timers to process. They're populating a shared bucket. If they're in a higher-level wheel you would need to linearly search them to find the minimum. But normally you only care about when the next cascade operation needs to occur, which is the minimum within the granularity of that wheel, and _that's_ O(1). See "Hashed and Hierarchical Timing Wheels: Data Structures for the Efficient Implementation of a Timer Facility" by George Varghese and Tony Lauck. And specifically appendix A for the O(1) expire.
- Someone 10y agohttp://www.cs.columbia.edu/~nahum/w6998/papers/ton97-timing-wheels.pdf http://www.cs.columbia.edu/~nahum/w6998/papers/ton97-timing-... In somewhat of a defense of "Implementing Software Timers", the code seems to be for an embedded system in 1990, as hinted at by the disabling of interrupts. Chances are it will not have hundreds of timers, and that code size may be more important than efficiency.