我有很多类都做同样的事情:它们在构造过程中接收一个标识符(数据库中的 PK),然后从数据库中加载。我正在尝试缓存这些类的实例,以尽量减少对数据库的调用。当缓存达到临界大小时,它应该丢弃那些最近最少访问的缓存对象。
缓存实际上似乎工作正常,但不知何故我无法确定缓存的内存使用情况(在后面的行中#Next line doesn't do what I expected
)。
到目前为止我的代码:
#! /usr/bin/python3.2
from datetime import datetime
import random
import sys
class Cache:
instance = None
def __new__ (cls):
if not cls.instance:
cls.instance = super ().__new__ (cls)
cls.instance.classes = {}
return cls.instance
def getObject (self, cls, ident):
if cls not in self.classes: return None
cls = self.classes [cls]
if ident not in cls: return None
return cls [ident]
def cache (self, object):
#Next line doesn't do what I expected
print (sys.getsizeof (self.classes) )
if object.__class__ not in self.classes:
self.classes [object.__class__] = {}
cls = self.classes [object.__class__]
cls [object.ident] = (object, datetime.now () )
class Cached:
def __init__ (self, cache):
self.cache = cache
def __call__ (self, cls):
cls.cache = self.cache
oNew = cls.__new__
def new (cls, ident):
cached = cls.cache ().getObject (cls, ident)
if not cached: return oNew (cls, ident)
cls.cache ().cache (cached [0] )
return cached [0]
cls.__new__ = new
def init (self, ident):
if hasattr (self, 'ident'): return
self.ident = ident
self.load ()
cls.__init__ = init
oLoad = cls.load
def load (self):
oLoad (self)
self.cache ().cache (self)
cls.load = load
return cls
@Cached (Cache)
class Person:
def load (self):
print ('Expensive call to DB')
print ('Loading Person {}'.format (self.ident) )
#Just simulating
self.name = random.choice ( ['Alice', 'Bob', 'Mallroy'] )
@Cached (Cache)
class Animal:
def load (self):
print ('Expensive call to DB')
print ('Loading Animal {}'.format (self.ident) )
#Just simulating
self.species = random.choice ( ['Dog', 'Cat', 'Iguana'] )
sys.getsizeof
返回有趣的值。
如何确定所有缓存对象的实际内存使用情况?