Python使用cachetools加速一些短时间重复的操作

cachetools这个包通过建立缓存来加速操作,当函数接收cache中存在的输入值时,直接用cache中缓存的值返回,不用进入函数。文档地址:https://pypi.org/project/cachetools/

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

不使用cachetools时:

import timeit

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

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))
                    num += 1
                    continue
    # print("素数对总数:%d" % num)

while True:
    n = int(input("输入任意大于2的偶数:"))
    if n==0:
        break
    print(timeit.timeit("prime2evens(n)",number=1000,globals=globals()))

输出:

输入任意大于2的偶数:100
0.08372574599343352
输入任意大于2的偶数:100
0.06929763199877925
输入任意大于2的偶数:100
0.08502391600632109
输入任意大于2的偶数:100
0.06750393500260543

使用cachetools时:

import timeit
from cachetools import cached, LRUCache, TTLCache

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=LRUCache(maxsize=32))
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))
                    num += 1
                    continue
    # print("素数对总数:%d" % num)

while True:
    n = int(input("输入任意大于2的偶数:"))
    if n==0:
        break
    print(timeit.timeit("prime2evens(n)",number=1000,globals=globals()))

输出:

输入任意大于2的偶数:100
0.0015404750010930002
输入任意大于2的偶数:100
0.0014256010035751387
输入任意大于2的偶数:100
0.0015083329926710576
输入任意大于2的偶数:100
0.0014453140029218048

对比发现,该例子上使用cachetools在耗时上有数量级下降。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值