fast_able/
statis.rs

1use std::{sync::Arc, time::Duration};
2
3/// Statistics utility, counts events per second and executes a callback
4/// 统计工具,统计每秒事件数并执行回调
5pub struct Statis {
6    _rt: std::thread::JoinHandle<()>,
7    sum: Arc<std::sync::atomic::AtomicU64>,
8}
9
10impl Statis {
11    /// Create a new Statis instance
12    /// 创建一个新的 Statis 实例
13    ///
14    /// # Arguments
15    /// * `print` - Callback function executed every second with the count of events
16    /// * `print` - 每秒执行的回调函数,参数为事件数量
17    pub fn new<P: Fn(u64) + Send + 'static>(print: P) -> Self {
18        let sum = Arc::new(std::sync::atomic::AtomicU64::new(0));
19        let sum_clone = sum.clone();
20        let rt = std::thread::spawn(move || loop {
21            std::thread::sleep(Duration::from_millis(1000));
22            let v = sum_clone.fetch_and(0, std::sync::atomic::Ordering::SeqCst);
23            if v > 0 {
24                print(v);
25            }
26        });
27        Self { _rt: rt, sum }
28    }
29
30    /// Increment the counter
31    /// 增加计数
32    pub fn add(&self) {
33        _ = self.sum.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
34    }
35}
36
37impl Drop for Statis {
38    fn drop(&mut self) {}
39}
40
41#[test]
42fn test() {
43    pub static RECKON_BY_SEC: once_cell::sync::Lazy<Statis> =
44        once_cell::sync::Lazy::new(|| Statis::new(|v| println!("one sec run sum: {v}")));
45
46    let rt = std::thread::spawn(|| {
47        for i in 0..10000_0000 {
48            RECKON_BY_SEC.add();
49        }
50    });
51    let rt2 = std::thread::spawn(|| {
52        for i in 0..10000_0000 {
53            RECKON_BY_SEC.add();
54        }
55    });
56    let rt3 = std::thread::spawn(|| {
57        for i in 0..10000_0000 {
58            RECKON_BY_SEC.add();
59        }
60    });
61
62    rt.join();
63    rt2.join();
64    rt3.join();
65}