1+ package main
2+
3+ import (
4+ "fmt"
5+ "time"
6+ )
7+
8+ // Example of how to use the improved directory cache with performance monitoring
9+ func ExampleCacheUsage () {
10+ // Create custom cache configuration
11+ cacheConfig := & CacheConfig {
12+ TTL : 2 * time .Minute , // Longer TTL for better performance
13+ CleanupInterval : 1 * time .Minute , // More frequent cleanup
14+ MaxEntries : 500 , // Smaller cache for this example
15+ EnablePeriodicCleanup : true ,
16+ }
17+
18+ // Create cache with custom configuration
19+ fs := & DefaultFileSystem {}
20+ cache := NewDirCache (cacheConfig , fs )
21+ defer cache .Close () // Important: close to stop cleanup goroutine
22+
23+ // Test some directory checks
24+ testDirs := []string {
25+ "/tmp" ,
26+ "/etc" ,
27+ "/var" ,
28+ "/usr/bin" ,
29+ "/nonexistent/dir" ,
30+ }
31+
32+ fmt .Println ("Testing directory cache performance..." )
33+
34+ // First round - cache misses
35+ start := time .Now ()
36+ for _ , dir := range testDirs {
37+ exists := cache .IsDirectoryNotEmpty (dir )
38+ fmt .Printf ("Directory %s exists and not empty: %v\n " , dir , exists )
39+ }
40+ firstRoundTime := time .Since (start )
41+
42+ // Second round - cache hits (should be much faster)
43+ start = time .Now ()
44+ for _ , dir := range testDirs {
45+ exists := cache .IsDirectoryNotEmpty (dir )
46+ fmt .Printf ("Directory %s exists and not empty: %v (cached)\n " , dir , exists )
47+ }
48+ secondRoundTime := time .Since (start )
49+
50+ // Get and display cache statistics
51+ stats := cache .GetStats ()
52+ fmt .Printf ("\n === Cache Performance Statistics ===\n " )
53+ fmt .Printf ("Cache Hits: %d\n " , stats .Hits )
54+ fmt .Printf ("Cache Misses: %d\n " , stats .Misses )
55+ fmt .Printf ("Hit Ratio: %.2f%%\n " , stats .HitRatio ()* 100 )
56+ fmt .Printf ("Total Entries: %d\n " , stats .TotalSize )
57+ fmt .Printf ("Evictions: %d\n " , stats .Evictions )
58+
59+ fmt .Printf ("\n === Performance Improvement ===\n " )
60+ fmt .Printf ("First round (cache misses): %v\n " , firstRoundTime )
61+ fmt .Printf ("Second round (cache hits): %v\n " , secondRoundTime )
62+ if secondRoundTime .Nanoseconds () > 0 {
63+ speedup := float64 (firstRoundTime .Nanoseconds ()) / float64 (secondRoundTime .Nanoseconds ())
64+ fmt .Printf ("Speedup: %.1fx faster with cache\n " , speedup )
65+ }
66+ }
67+
68+ // Uncomment to run the example:
69+ // func main() {
70+ // ExampleCacheUsage()
71+ // }
0 commit comments