Python使用cachetools实现增加和查询共用同一个cache

在前一篇文章中介绍了可以提高查询效率的cachetools包:Python使用cachetools加速一些短时间重复的操作

但是这里的方法只针对查询,如果创建时也把“输入-输出”关系保存在cache中,那么创建过但是没有查询过的输入也可以立马得到结果,尤其是有时创建后短时间内就要查询的情况。这样还可以避免redis、es等先写后查的一致性问题。

还是加速一个偶数分解为两个素数之和的例子:

import timeit
from cachetools import cached, LRUCache, TTLCache, keys

lru = LRUCache(maxsize=0xffff)#需要共用同一个cache

def a(h):
    x = 0
    for j in range(2, h):
        if h % j == 0:
            x = 1
            break
    if x == 0:
        return 1

@cached(cache=lru)#这时cache使用创建时的同一个cache
def prime2evens(n):
    num = 0
    if n % 2 == 0:
        for k in range(2, int(n / 2) + 1):
            if a(k) == 1 and a(n - k) == 1:
                h = 1
                if h == 0:
                    print("%d can't" % n)
                    break
                else:
                    # print("%d=%d+%d" % (n, k, n - k))8.431100286543369e-05
                    num += 1
                    continue
    return num


while True:
    n = int(input("输入任意大于2的偶数:"))
    if n == 0:
        break

    lru[n] = 8 #相当于创建,因为LRUCache()有__setitem__方法,所以可以直接用键值对指定

    print(timeit.timeit("print(prime2evens(n))", number=2, globals=globals()))

输出:

输入任意大于2的偶数:100
6
6
0.00019842598703689873

可以发现我们指定的8没有生效,还是正确执行后的结果6。

这是因为装饰器cached函数对输入进行了hash计算,我们可以看源码:

def cached(cache, key=keys.hashkey, lock=None):
    """Decorator to wrap a function with a memoizing callable that saves
    results in a cache.

    """
    ......

因为key=keys.hashkey,所以我们写的是lru[n]=8的key是n,但是执行时输入的n被转换为keys.hashkey(n),两个key对不上,当然不会返回我们设定的8了。

解决这个问题有两个办法:

1 将lru[n] = 8改为lru[keys.hashkey(n)] = 8

2 将@cached(cache=lru)改为@cached(cache=lru,key=lambda x:x),即使用我们指定的“hash算法”,用输入自身作为key。

除此之外,我们还可以不用装饰器,直接利用LRUCache添加和查询(或者自己将它封装为装饰器),需要改写prime2evens()如下:

def prime2evens(n):
    if (ans:=lru.get(n)) is not None:
         return ans
    num = 0
    if n % 2 == 0:
        for k in range(2, int(n / 2) + 1):
            if a(k) == 1 and a(n - k) == 1:
                h = 1
                if h == 0:
                    print("%d can't" % n)
                    break
                else:
                    # print("%d=%d+%d" % (n, k, n - k))8.431100286543369e-05
                    num += 1
                    continue
    lru[n] = num
    return num

如果写成装饰器如下:

def lrucache(func):
    def wrapper(*args, **kwargs):
        value = lru.get(args[0])
        if value is not None:
            return value
        lru[args[0]] = value = func(*args, **kwargs)
        return value
    return wrapper
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值