Simple Cache - improvements?

rav at smo3k.z.pl rav at smo3k.z.pl
Tue May 4 09:27:00 EDT 1999


Hello,
Below is very simple cache implementation. There is no LRU, MRU,
no predictor or other features. Nothing but cache.
I'm interested in improvements to this code. It could
be useful - not only for me, I hope :-)
Rafal Smotrzyk

#code-start
import whrandom

class MSimpleCache:
   def __init__(self,agetfunc,amaxlen=100):
      self.GetValue=agetfunc
      self.MaxLen=amaxlen
      self.VDict={}
      self.KDict={}
      self.VPos=1
      self.AccessRatio=0
      self.HitRatio=0
   def __getitem__(self,key):
      self.AccessRatio=self.AccessRatio+1
      id=self.KDict.get(key,0)
      if id:
         self.HitRatio=self.HitRatio+1
         return self.VDict[id][1]
      else:
         v=self.VDict.get(self.VPos,0)
         if v:
            del self.KDict[v[0]]
         ret=self.GetValue(key)
         self.VDict[self.VPos]=[key,ret]
         self.KDict[key]=self.VPos
         self.VPos=self.VPos+1
         if self.VPos>self.MaxLen:
            self.VPos=1
         return ret
   def dump(self):
      print 'Access ratio:',self.AccessRatio
      print 'Hit ratio:',self.HitRatio
      print 'Hit %:',100.0*self.HitRatio/self.AccessRatio
      print 'VDict len:',len(self.VDict.keys())
      print 'KDict len:',len(self.KDict.keys())

# cached operation - sample
def GetCalculatedValue(key):
   x=`key`+'aaaa'
   y=key*0.5
   z=x+`y`
   return z

# models of distribution max=1000 def GetLinear(key):  return key def
GetRandom(key):  return whrandom.randint(1,max)
l1,l2,l3=whrandom.randint(1,max),whrandom.randint(1,max),whrandom.randint(1,m
ax) def GetNDist(key):	global l1,l2,l3 
l1,l2,l3=l2,l3,whrandom.randint(1,max)	return int((l1+l2+l3)/3)

#test...
for aname,afunc in
[['Linear',GetLinear],['Random',GetRandom],['NDist',GetNDist]]:
   acache=MSimpleCache(GetCalculatedValue,250)
   for i in range(1000):
      k=afunc(i)
      x=acache[k]
      y=GetCalculatedValue(k)
      if x!=y:
         print 'ValueError:',k,x,y
   print 'Name:',aname
   acache.dump()
   print

#code-end

#output-start
Name: Linear
Access ratio: 1000
Hit ratio: 0
Hit %: 0.0
VDict len: 250
KDict len: 250

Name: Random
Access ratio: 1000
Hit ratio: 221
Hit %: 22.1
VDict len: 250
KDict len: 250

Name: NDist
Access ratio: 1000
Hit ratio: 355
Hit %: 35.5
VDict len: 250
KDict len: 250
#output-end

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/       Search, Read, Discuss, or Start Your Own    




More information about the Python-list mailing list