1+ from collections import OrderedDict
2+ from libcachesim import PluginCache , CommonCacheParams , Request , SyntheticReader , LRU
3+
4+ class StandaloneLRU :
5+ def __init__ (self ):
6+ self .cache_data = OrderedDict ()
7+
8+ def cache_hit (self , obj_id ):
9+ if obj_id in self .cache_data :
10+ obj_size = self .cache_data .pop (obj_id )
11+ self .cache_data [obj_id ] = obj_size
12+
13+ def cache_miss (self , obj_id , obj_size ):
14+ self .cache_data [obj_id ] = obj_size
15+
16+ def cache_eviction (self ):
17+ evicted_id , _ = self .cache_data .popitem (last = False )
18+ return evicted_id
19+
20+ def cache_remove (self , obj_id ):
21+ if obj_id in self .cache_data :
22+ del self .cache_data [obj_id ]
23+
24+
25+ def cache_init_hook (common_cache_params : CommonCacheParams ):
26+ return StandaloneLRU ()
27+
28+ def cache_hit_hook (cache , obj_id ):
29+ cache .cache_hit (obj_id )
30+
31+ def cache_miss_hook (cache , request : Request ):
32+ cache .cache_miss (request .obj_id , request .obj_size )
33+
34+ def cache_eviction_hook (cache ):
35+ return cache .cache_eviction ()
36+
37+ def cache_remove_hook (cache , obj_id ):
38+ cache .cache_remove (obj_id )
39+
40+ def cache_free_hook (cache ):
41+ cache .cache_data .clear ()
42+
43+ plugin_lru_cache = PluginCache (
44+ cache_size = 1024 * 1024 ,
45+ cache_init_hook = cache_init_hook ,
46+ cache_hit_hook = cache_hit_hook ,
47+ cache_miss_hook = cache_miss_hook ,
48+ cache_eviction_hook = cache_eviction_hook ,
49+ cache_remove_hook = cache_remove_hook ,
50+ cache_free_hook = cache_free_hook ,
51+ cache_name = "CustomizedLRU" )
52+
53+ ref_lru_cache = LRU (cache_size = 1024 * 1024 )
54+
55+ reader = SyntheticReader (
56+ num_of_req = 100000 ,
57+ num_objects = 100 ,
58+ obj_size = 100 ,
59+ seed = 42 ,
60+ alpha = 0.8 ,
61+ dist = "zipf" ,
62+ )
63+
64+ for req in reader :
65+ plugin_hit = plugin_lru_cache .get (req )
66+ ref_hit = ref_lru_cache .get (req )
67+ assert plugin_hit == ref_hit , f"Cache hit mismatch: { plugin_hit } != { ref_hit } "
68+
69+ print ("All requests processed successfully. Plugin cache matches reference LRU cache." )
70+
71+
72+
0 commit comments