Skip to content

Repository files navigation

timer-benchmark

测试不同的数据结构(最小堆、四叉堆、红黑树、时间轮)实现的定时器的性能差异。

as Hashed and Hierarchical Timing Wheels implies

a timer module has 3 component routines:

// start a timer that will expire after `interval` unit of time// return an unique id of the pending timerintStart(interval, expiry_action)
// cancel a timer identified by `timer_id`
void Cancel(timer_id)
// per-tick bookking routine// in single-thread timer scheduler implementions, this routine will run timeout actions
int Update(now)

use min-heap, quaternary heap( 4-ary heap ), balanced binary search tree( red-black tree ), hashed timing wheel and Hierarchical timing wheel to implement different time scheduler.

Big(O) complexity of algorithm

FIFO means whether same deadline timers expire in FIFO order.

FIFO的意思是相同到期时间的定时器是否按FIFO的顺序到期

algoStart()Cancel()Tick()FIFOimplementation file
binary heap最小堆O(log N)O(log N)O(1)noPriorityQueueTimer
4-ary heap四叉堆O(log N)O(log N)O(1)noQuatHeapTimer
redblack tree红黑树O(log N)O(log N)O(log N)noRBTreeTimer
hashed timing wheel时间轮O(1)O(1)O(1)yesHashedWheelTimer
hierarchical timing wheel多级时间轮O(1)O(1)O(1)yesHHWheelTimer

How To Build

Obtain CMake

Obtain CMake first.

  • apt/yum/brew install cmake on Linux/MacOS
  • choco install cmake on Windows use choco

run shell command

  • mkdir cmake-build; cd cmake-build && cmake -DCMAKE_BUILD_TYPE=Release .. && cmake --build .

Benchmarks

Benchmark result

Win10 x64 6-core 3.93MHz CPU

BenchmarkTimeCPUIterations
BM_PQTimerAdd441 ns433 ns1947826
BM_QuadHeapTimerAdd429 ns427 ns1866667
BM_RBTreeTimerAdd1231 ns1228 ns1120000
BM_HashWheelTimerAdd430 ns436 ns1792000
BM_HHWheelTimerAdd669 ns672 ns1000000
BM_PQTimerCancel668 ns656 ns1000000
BM_QuadHeapTimerCancel351 ns349 ns2240000
BM_RBTreeTimerCancel1685 ns1692 ns896000
BM_HashWheelTimerCancel632 ns641 ns1000000
BM_HHWheelTimerCancel942 ns953 ns1000000
BM_PQTimerTick29.8 ns29.8 ns23578947
BM_QuadHeapTimerTick30.3 ns30.5 ns23578947
BM_RBTreeTimerTick30.2 ns29.8 ns23578947
BM_HashWheelTimerTick31.2 ns30.8 ns21333333
BM_HHWheelTimerTick30.5 ns30.7 ns22400000

Conclusion

  • rbtree timer Add/Cancel has not so good performance compare to other implementations;
  • 红黑树的插入和删除相比其它实现,表现都弱了一些;
  • binary min heap is a good choice, easy to implement and have a good performance, but without FIFO expiration order(heap sort is unstable);
  • 最小堆是一个不错的选择,代码实现简单性能也不俗,但不支持相同超时的定时器按FIFO顺序触发;

Reference

About

Benchmark of different timer implementations(min-heap, red-black tree, timing wheel) 不同数据结构实现的定时器测试

Topics

Resources

Stars

149 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages