CacheStats

Struct CacheStats 

Source
pub struct CacheStats {
    pub hits: u64,
    pub misses: u64,
    pub evictions: u64,
    pub invalidations: u64,
}
Expand description

Cache statistics for monitoring and debugging.

Fields§

§hits: u64

Total cache hits

§misses: u64

Total cache misses

§evictions: u64

Total evictions due to size limit

§invalidations: u64

Total invalidations due to file changes

Implementations§

Source§

impl CacheStats

Source

pub fn hit_ratio(&self) -> f64

Calculate cache hit ratio.

Examples found in repository?
examples/caching_performance.rs (line 167)
130fn demonstrate_loader_caching() -> Result<(), Box<dyn std::error::Error>> {
131    println!("4. Advanced Loader with Caching:");
132    
133    // Configure loader with caching enabled
134    let loader_config = LoaderConfig {
135        enable_caching: true,
136        cache_config: CacheConfig {
137            max_size: 100,
138            max_age: Some(Duration::from_secs(600)), // 10 minutes
139            track_file_changes: true,
140            enable_stats: true,
141        },
142        ..LoaderConfig::default()
143    };
144    
145    let mut loader = TemplateLoader::with_config(loader_config);
146    
147    // Load templates with caching
148    println!("   - Loading templates from directory (with caching)...");
149    let start = Instant::now();
150    let templates = loader.load_from_directory("templates")?;
151    let first_load_time = start.elapsed();
152    
153    println!("   - First load: {} templates in {:?}", templates.len(), first_load_time);
154    println!("   - Cache size: {}", loader.cache_size());
155    
156    // Load again to test cache performance  
157    let start = Instant::now();
158    let _templates = loader.load_from_directory("templates")?;
159    let cached_load_time = start.elapsed();
160    
161    println!("   - Cached load: {:?} ({}x faster)", 
162             cached_load_time,
163             first_load_time.as_nanos() / cached_load_time.as_nanos().max(1));
164    
165    // Show cache statistics
166    if let Some(stats) = loader.cache_stats() {
167        println!("   - Cache hit ratio: {:.2}%", stats.hit_ratio() * 100.0);
168        println!("   - Total hits: {}, misses: {}", stats.hits, stats.misses);
169    }
170    
171    println!();
172    Ok(())
173}
174
175fn demonstrate_cache_monitoring() -> Result<(), Box<dyn std::error::Error>> {
176    println!("5. Cache Statistics and Monitoring:");
177    
178    let cache = TemplateCache::with_config(CacheConfig {
179        enable_stats: true,
180        max_size: 10,
181        ..CacheConfig::default()
182    });
183    
184    // Generate some cache activity
185    let templates = vec![
186        "Template A: @[content]@",
187        "Template B: @[data]@",
188        "Template C: @[info]@",
189        "Template D: @[value]@",
190        "Template E: @[result]@",
191    ];
192    
193    // Insert templates
194    for template_content in &templates {
195        let template = TronTemplate::new(template_content)?;
196        cache.insert_template(template)?;
197    }
198    
199    // Create cache hits and misses
200    for _ in 0..10 {
201        // Cache hits
202        let _hit = cache.get_by_content(templates[0]);
203        let _hit = cache.get_by_content(templates[1]);
204        
205        // Cache misses
206        let _miss = cache.get_by_content("Nonexistent template @[x]@");
207    }
208    
209    // Add more templates to trigger eviction
210    for i in 6..15 {
211        let template = TronTemplate::new(&format!("Template {}: @[data]@", i))?;
212        cache.insert_template(template)?;
213    }
214    
215    // Display comprehensive statistics
216    if let Some(stats) = cache.stats() {
217        println!("   - Cache Performance Metrics:");
218        println!("     * Total requests: {}", stats.hits + stats.misses);
219        println!("     * Cache hits: {}", stats.hits);
220        println!("     * Cache misses: {}", stats.misses);
221        println!("     * Hit ratio: {:.2}%", stats.hit_ratio() * 100.0);
222        println!("     * Evictions: {}", stats.evictions);
223        println!("     * Invalidations: {}", stats.invalidations);
224    }
225    
226    println!("   - Current cache size: {}", cache.size());
227    println!("   - Cache is empty: {}", cache.is_empty());
228    
229    // Clean up expired entries
230    cache.cleanup_expired();
231    println!("   - After cleanup: {} templates", cache.size());
232    
233    println!();
234    Ok(())
235}
Source

pub fn reset(&mut self)

Reset all statistics to zero.

Trait Implementations§

Source§

impl Clone for CacheStats

Source§

fn clone(&self) -> CacheStats

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for CacheStats

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for CacheStats

Source§

fn default() -> CacheStats

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.