Coverage for ion/util/cache : 72.55%
Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
|
#!/usr/bin/env python
@file ion/util/cache.py @author Adam R. Smith @brief Simple caching utilities. """
""" Memoize with timeout. This has been optimized repeatedly to squeeze out extra performance.
http://code.activestate.com/recipes/325905/ (r5) Modified by Adam R. Smith """
"""Clear cache of results which have timed out""" for func in self._caches: cache = {} for key in self._caches[func]: if (self._timeouts[func] <= 0) or ((time() - self._caches[func][key][1]) < self._timeouts[func]): cache[key] = self._caches[func][key] self._caches[func] = cache
cached = False #func.func_name = f.func_name
""" Amortized O(1) LRU cache with a dict-like interface. Based on http://code.activestate.com/recipes/252524/ (r3) Copyright 2003 Josiah Carlson. Modified by Adam R. Smith to support sizes and to be more dict-like. Licensed under the PSF License: http://docs.python.org/license.html """
""" limit is either an integer item count or a size in bytes. """
self[key] = value
return len(self.d)
if self.first == self.last: self.first = None self.last = None self.total_size = 0 return
a = self.first self.total_size -= a.size a.next.prev = None self.first = a.next a.next = None
nobj = self.d[a.me[0]] obj = nobj.me[1] if hasattr(obj, 'clear'): obj.clear()
del self.d[a.me[0]] del a
else: else:
cur = self.first while cur != None: cur2 = cur.next yield cur.me[1] cur = cur2
return iter(self.d)
for i,j in self.iteritems(): yield j
""" Recalculate the size of the object at the given key, and update its access time. """ val = self[key] if self.use_size and hasattr(val, '__sizeof__'): old_size = val.size val.size = val.__sizeof__() self.total_size += val.size - old_size
self.purge() return val
for k,v in d.iteritems(): self[k] = v
# Remove for code coverage ''' if __name__ == '__main__': def main(): class ObjectWithSize(object): def __init__(self, size): self.size = size def __sizeof__(self): return self.size
lru = LRUDict(3) lru['a'] = 1 lru['b'] = 2 lru['c'] = 3 lru['a'] = 1 lru['d'] = 4 print 'Should be: a, c, d', lru.keys()
lru = LRUDict(limit=100, use_size=True) lru['a'] = ObjectWithSize(25) lru['b'] = ObjectWithSize(50) lru['c'] = ObjectWithSize(25) lru['d'] = ObjectWithSize(1) print 'Should be: c, b, d', lru.keys()
lru.touch('b') lru.touch('c') lru['a'] = ObjectWithSize(25) print 'Should be: a, c, b', lru.keys()
lru.update({'e': ObjectWithSize(1), 'f': ObjectWithSize(2), 'g': ObjectWithSize(20)})
for k,v in lru.iteritems(): print '%s: %s' % (k, str(v))
lru.clear() print 'Should be empty: ', lru.keys()
print 'Should be false: ', lru.has_key('monkey')
main() |