-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathcaches.py
304 lines (254 loc) · 10.6 KB
/
caches.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#! /usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'linkerlin'
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import collections
import functools
from itertools import ifilterfalse
from heapq import nsmallest
from operator import itemgetter
import threading
import cPickle as p
import datetime as dt
import base64
import random
import time
from hashlib import md5
class Counter(dict):
'Mapping where default values are zero'
def __missing__(self, key):
return 0
def sqlite_cache(timeout_seconds=100, cache_none=True, ignore_args={}):
import sqlite3
def decorating_function(user_function,
len=len, iter=iter, tuple=tuple, sorted=sorted, KeyError=KeyError):
with sqlite3.connect(u"cache.sqlite") as cache_db:
cache_cursor = cache_db.cursor()
cache_table = u"table_" + user_function.func_name
#print cache_table
cache_cursor.execute(
u"CREATE TABLE IF NOT EXISTS " + cache_table
+ u" (key CHAR(36) PRIMARY KEY, value TEXT, update_time timestamp);")
cache_db.commit()
kwd_mark = object() # separate positional and keyword args
lock = threading.Lock()
@functools.wraps(user_function)
def wrapper(*args, **kwds):
result = None
cache_db = None
# cache key records both positional and keyword args
key = args
if kwds:
real_kwds = []
for k in kwds:
if k not in ignore_args:
real_kwds.append((k, kwds[k]))
key += (kwd_mark,)
if len(real_kwds) > 0:
key += tuple(sorted(real_kwds))
while cache_db is None:
try:
with lock:
cache_db = sqlite3.connect(u"cache.sqlite")
except sqlite3.OperationalError as ex:
print ex
time.sleep(0.05)
# get cache entry or compute if not found
try:
cache_cursor = cache_db.cursor()
key_str = str(key) # 更加宽泛的Key,只检查引用的地址,而不管内容,“浅”检查,更好的配合方法,但是可能会出现过于宽泛的问题
key_str = md5(key_str).hexdigest() # base64.b64encode(key_str)
#print "key_str:", key_str[:60]
with lock:
cache_cursor.execute(
u"select * from " + cache_table
+ u" where key = ? order by update_time desc", (key_str,))
for record in cache_cursor:
dump_data = base64.b64decode(record[1])
result = p.loads(dump_data)
#print "cached:", md5(result).hexdigest()
break
if result is not None:
with lock:
wrapper.hits += 1
print "hits", wrapper.hits, "miss", wrapper.misses, wrapper
else:
result = user_function(*args, **kwds)
if result is None and cache_none == False:
return
value = base64.b64encode(p.dumps(result, p.HIGHEST_PROTOCOL))
while 1:
try:
cache_cursor.execute(u"REPLACE INTO " + cache_table + u" VALUES(?,?,?)",
(key_str, value, dt.datetime.now()))
except sqlite3.OperationalError as ex:
print ex, "retry update db."
else:
cache_db.commit()
with lock:
wrapper.misses += 1
break
finally:
if random.random() > 0.999:
timeout = dt.datetime.now() - dt.timedelta(seconds=timeout_seconds)
with lock:
cache_cursor.execute(u"DELETE FROM " + cache_table + u" WHERE update_time < datetime(?)",
(str(timeout),))
with lock:
cache_db.commit()
cache_db.close()
return result
def clear():
with lock:
wrapper.hits = wrapper.misses = 0
wrapper.hits = wrapper.misses = 0
wrapper.clear = clear
return wrapper
return decorating_function
def lru_cache(maxsize=100, cache_none=True, ignore_args=[]):
'''Least-recently-used cache decorator.
Arguments to the cached function must be hashable.
Cache performance statistics stored in f.hits and f.misses.
Clear the cache with f.clear().
http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
'''
maxqueue = maxsize * 10
def decorating_function(user_function,
len=len, iter=iter, tuple=tuple, sorted=sorted, KeyError=KeyError):
cache = {} # mapping of args to results
queue = collections.deque() # order that keys have been used
refcount = Counter() # times each key is in the queue
sentinel = object() # marker for looping around the queue
kwd_mark = object() # separate positional and keyword args
# lookup optimizations (ugly but fast)
queue_append, queue_popleft = queue.append, queue.popleft
queue_appendleft, queue_pop = queue.appendleft, queue.pop
lock = threading.RLock()
@functools.wraps(user_function)
def wrapper(*args, **kwds):
with lock:
# cache key records both positional and keyword args
key = args
if kwds:
real_kwds = []
for k in kwds:
if k not in ignore_args:
real_kwds.append((k, kwds[k]))
key += (kwd_mark,)
if len(real_kwds) > 0:
key += tuple(sorted(real_kwds))
#print "key", key
# record recent use of this key
queue_append(key)
refcount[key] += 1
# get cache entry or compute if not found
try:
result = cache[key]
wrapper.hits += 1
#print "hits", wrapper.hits, "miss", wrapper.misses, wrapper
except KeyError:
result = user_function(*args, **kwds)
if result is None and cache_none == False:
return
cache[key] = result
wrapper.misses += 1
# purge least recently used cache entry
if len(cache) > maxsize:
key = queue_popleft()
refcount[key] -= 1
while refcount[key]:
key = queue_popleft()
refcount[key] -= 1
if key in cache:
del cache[key]
if key in refcount:
refcount[key]
finally:
pass
# periodically compact the queue by eliminating duplicate keys
# while preserving order of most recent access
if len(queue) > maxqueue:
refcount.clear()
queue_appendleft(sentinel)
for key in ifilterfalse(refcount.__contains__,
iter(queue_pop, sentinel)):
queue_appendleft(key)
refcount[key] = 1
return result
def clear():
cache.clear()
queue.clear()
refcount.clear()
wrapper.hits = wrapper.misses = 0
wrapper.hits = wrapper.misses = 0
wrapper.clear = clear
return wrapper
return decorating_function
def lfu_cache(maxsize=100):
'''Least-frequenty-used cache decorator.
Arguments to the cached function must be hashable.
Cache performance statistics stored in f.hits and f.misses.
Clear the cache with f.clear().
http://en.wikipedia.org/wiki/Least_Frequently_Used
'''
def decorating_function(user_function):
cache = {} # mapping of args to results
use_count = Counter() # times each key has been accessed
kwd_mark = object() # separate positional and keyword args
lock = threading.RLock()
@functools.wraps(user_function)
def wrapper(*args, **kwds):
with lock:
key = args
if kwds:
key += (kwd_mark,) + tuple(sorted(kwds.items()))
use_count[key] += 1
# get cache entry or compute if not found
try:
result = cache[key]
wrapper.hits += 1
except KeyError:
result = user_function(*args, **kwds)
cache[key] = result
wrapper.misses += 1
# purge least frequently used cache entry
if len(cache) > maxsize:
for key, _ in nsmallest(maxsize // 10,
use_count.iteritems(),
key=itemgetter(1)):
del cache[key], use_count[key]
return result
def clear():
cache.clear()
use_count.clear()
wrapper.hits = wrapper.misses = 0
wrapper.hits = wrapper.misses = 0
wrapper.clear = clear
return wrapper
return decorating_function
if __name__ == '__main__':
@lru_cache(maxsize=20, ignore_args=["y"])
def f(x, y):
return 3 * x + y
domain = range(5)
from random import choice
for i in range(1000):
r = f(choice(domain), y=choice(domain))
print(f.hits, f.misses)
@lfu_cache(maxsize=20)
def f(x, y):
return 3 * x + y
domain = range(5)
from random import choice
for i in range(1000):
r = f(choice(domain), choice(domain))
print(f.hits, f.misses)
@sqlite_cache()
def f2(x, y):
return 3 * x + y
domain = range(50)
for i in range(1000):
r = f2(choice(domain), y=choice(domain))
print(f2.hits, f2.misses)