5
Created by David Farrar on 2012-12-27.
6
Copyright (c) 2009-2013 Exa Networks. All rights reserved.
13
def __init__ (self, min_items=10, max_items=2000, cache_life=3600):
16
self.min_items = min_items
17
self.max_items = max_items
18
self.cache_life = cache_life
19
self.last_accessed = int(time.time())
21
def cache (self, key, value):
22
now = int(time.time())
24
if now - self.last_accessed >= self.cache_life:
25
self.truncate(self.min_items)
27
elif len(self) >= self.max_items:
28
self.truncate(self.max_items/2)
31
self.ordered.append(key)
33
self.last_accessed = now
38
def retrieve (self, key):
39
now = int(time.time())
42
if now - self.last_accessed >= self.cache_life:
43
self.truncate(self.min_items)
45
# only update the access time if we modified the cache
46
self.last_accessed = now
50
def truncate (self, pos):
51
pos = len(self.ordered) - pos
52
expiring = self.ordered[:pos]
53
self.ordered = self.ordered[pos:]
58
if __name__ == '__main__':
60
def __init__ (self, data):
63
class klass2 (object):
64
def __init__ (self, data):
68
def __init__ (self, data):
76
def __init__ (self, data):
84
def __init__ (self, data):
88
class _kparent2 (object):
89
def __init__ (self, data):
93
class klass5 (_kparent1):
94
def __init__ (self, data):
95
_kparent1.__init__(self,data)
100
class klass6 (_kparent2):
101
def __init__ (self, data):
102
_kparent2.__init__(self,data)
107
class klass7 (klass6):
110
class klass8 (klass6):
111
def __init__ (self, data):
112
klass6.__init__(self,data)
113
self.s = self.a + self.b + self.c + self.d + self.e
115
class klass9 (klass6):
116
def __init__ (self, data):
117
klass6.__init__(self,data)
118
self.s1 = self.a + self.b + self.c + self.d + self.e
119
self.s2 = self.b + self.c + self.d + self.e
120
self.s3 = self.c + self.d + self.e
121
self.s4 = self.d + self.e
122
self.s5 = self.a + self.b + self.c + self.d
123
self.s6 = self.a + self.b + self.c
124
self.s7 = self.a + self.b
130
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:"|;<>?,./[]{}-=_+!@£$%^&*()'
132
from random import choice
134
while len(samples) != UNIQUE:
135
samples.add(choice(chars)+choice(chars)+choice(chars)+choice(chars)+choice(chars))
137
samples = list(samples)
139
for klass in [klass1,klass2,klass3,klass4,klass5,klass6,klass7,klass8,klass9]:
143
for val in xrange(COUNT):
145
_ = klass(samples[val])
149
print COUNT,'iterations of',klass.__name__,'with',UNIQUE,'uniques classes'
150
print "time instance %d" % time1
154
for val in xrange(COUNT):
158
_ = cache.retrieve(val)
160
_ = cache.cache(val, klass(samples[val]))
165
print "time cached %d" % time2
166
print "speedup %.3f" % (time1/time2)