Skip to content

Commit

Permalink
timer
Browse files Browse the repository at this point in the history
  • Loading branch information
tickbh committed Jun 11, 2024
1 parent 6ee7e8e commit f4f1974
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ name = "algorithm"
version = "0.1.3"
edition = "2021"
authors = ["tickbh <[email protected]>"]
description = "about algorithm data structure, now has lru/lru-k/lfu/slab/rbtree/roaring_bitmap, 关于算法常用的数据结构"
description = "about algorithm data structure, now has lru/lru-k/lfu/slab/rbtree/roaring_bitmap/timer_wheelss, 关于算法常用的数据结构"
repository = "https://github.com/tickbh/algorithm-rs"
license = "Apache-2.0"
keywords = ["algorithm", "lru", "lfu", "lru-k", "slab"]
keywords = ["algorithm", "lru", "lfu", "timerwheel", "slab"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Expand Down
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,48 @@ fn main() {
algorithm: all cost times 132ms, sum = 18446744063712505088
tokio::slab: all cost times 477ms, sum = 18446744063712505088
normal alloc: all cost times 337ms, sum = 18446744063712505088
```

# 计时器轮(TimerWheel),模拟时钟格式组成的高效计时器

1. **环形数据结构**:TimerWheel,即时间轮,是一个环形的数据结构,类似于时钟的面,被等分为多个格子或槽位(slot)。

2. **槽位时间间隔**:每个槽位代表一个固定的时间间隔,例如1毫秒、1秒等。这个时间间隔决定了定时器的精度。

3. **初始化**:在算法开始时,需要初始化时间轮,包括设定时间轮的大小(即槽位的数量)和每个槽位代表的时间间隔。即当插入数据后即不允许修改时轮信息。

```rust
use algorithm::TimerWheel;

fn main() {
let mut timer = TimerWheel::new();
timer.append_timer_wheel(12, 60 * 60, "HourWheel");
timer.append_timer_wheel(60, 60, "MinuteWheel");
timer.append_timer_wheel(60, 1, "SecondWheel");

timer.add_timer(30);
assert_eq!(timer.get_delay_id(), 30);
timer.add_timer(149);
assert_eq!(timer.get_delay_id(), 30);
let t = timer.add_timer(600);
assert_eq!(timer.get_delay_id(), 30);
timer.add_timer(1);
assert_eq!(timer.get_delay_id(), 1);
timer.del_timer(t);
timer.add_timer(150);
assert_eq!(timer.get_delay_id(), 1);

let val = timer.update_deltatime(30).unwrap();
assert_eq!(val, vec![1, 30]);

timer.add_timer(2);

let val = timer.update_deltatime(119).unwrap();
assert_eq!(val, vec![2, 149]);

let val = timer.update_deltatime(1).unwrap();
assert_eq!(val, vec![150]);

assert!(timer.is_empty());
}
```

0 comments on commit f4f1974

Please sign in to comment.