update_rate/lib.rs
1//! This crate provides a utility for counting updates, for instance frame rates.
2//!
3//! Implementors of the `RateCounter` trait have a
4//! method, `.update()`, which is meant to be called every time your system
5//! updates (e.g. every frame, every physics update, etc).
6//!
7//! The trait `RateCounterImmut` adds an immutable update method which consumes
8//! the rate counter and returns an updated one.
9//!
10//! This can also be done immutably using shadowing and `.update_immut()`.
11//!
12//! # Examples
13//! The one important thing to remember is to call your Counter's `update()`
14//! (or `update_immut()`) at the beginning of your cycles.
15//!
16//! ```
17//! use update_rate::{RateCounter, DiscreteRateCounter};
18//! // Create a new DiscreteRateCounter with a sample rate of 10 updates
19//! let mut c = DiscreteRateCounter::new(10);
20//!
21//! for _ in 1..11 {
22//! c.update();
23//! // Rate should be 100 Hz with 10 ms/update
24//! std::thread::sleep(std::time::Duration::from_millis(10));
25//! }
26//!
27//! let difference = 100.0 - c.rate();
28//! println!("Rate was {}", c.rate());
29//! assert!(difference < 10.0, "Counter rate should be closer to actual rate.");
30//! ```
31mod base;
32pub use base::DiscreteRateCounter;
33
34mod rolling;
35pub use rolling::RollingRateCounter;
36
37mod format;
38pub use format::*;
39
40/// Basic rate counter functionality.
41///
42/// Types which implement RateCounter also implement Display (a string with "<cycles> Hz") and Debug (including samples as well).
43pub trait RateCounter {
44 /// Return the current number of samples the UpdateRateCounter is measuring.
45 fn samples(&self) -> u64;
46
47 /// Set the number of updates which the UpdateRateCounter considers.
48 ///
49 /// # Panics
50 /// This function may panic if given a `samples` value equal to 0.
51 fn set_samples(&mut self, samples: u64);
52
53 /// Updates the struct in place, but requires a mutable binding.
54 /// Call either this OR `update_immut()` at the beginning of each
55 /// cycle of the periodic activity being measured.
56 fn update(&mut self);
57
58 /// Return the last calculated rate of operation, in Hertz (updates per
59 /// second).
60 fn rate(&self) -> f64;
61}
62
63/// Immutable extensions for rate counters.
64pub trait RateCounterImmut: RateCounter {
65 /// Consumes the struct and returns an updated version.
66 /// Call either this OR `update()` at the beginning of
67 /// each cycle of the periodic activity being measured.
68 fn update_immut(self) -> Self;
69}