首页 > 编程知识 正文

Python CacheTools 模块

时间:2023-11-26 13:13:13 阅读:309406 作者:YWEJ

我们大多数人都会听到“缓存”这个词,但不是所有听到这个词的人都知道它。就计算机技术而言,缓存是存储数据(用户在计算机上执行的活动)的软件或硬件组件。当将来对相同的数据提出请求时,这非常有帮助,因为这样,相同的数据将得到更快的服务。存储在系统的缓存组件中的数据可能是因为之前执行的计算,或者相同数据的副本存储在其他地方。这就是我们如何看到高速缓存对于更快的计算速度和更短的时间内获得更好的结果是多么重要。与数据的实际大小相比,缓存占用的空间很小,因此对用户来说更有用。

Python 为我们提供了各种模块,通过这些模块,我们可以处理系统中存在的缓存内存。Python 还为我们提供了模块,在这些模块中,我们可以使用高速缓存来加快计算速度并节省时间。这样的 Python 模块之一是 Python 中的 Cachetools 模块,我们将在本教程中学习这个模块。我们将简要详细地了解 CacheTools 模块&它在 Python 中的功能,以及这些功能如何在系统中存在的缓存的帮助下帮助执行各种任务。

Python 中的 CacheTools 模块

CacheTools 模块:简介

Cachetools 是一个 Python 模块,它为我们提供了各种装饰器(这是这个模块中可用的功能)和记忆集合。缓存工具帮助我们有效地处理系统中存在的缓存,我们可以将该缓存与 CacheTools 模块一起使用,以更快地处理 Python 程序。Cachetools 模块还包括 Functools 模块(另一个 Python 模块)的@lru_cache 装饰函数的一些变体。

CacheTools 模块:安装

Cachetools Module 不是 Python 的内置模块,因此如果我们想在我们的系统中使用这个模块及其功能,我们必须先安装这个模块。在本节中,我们将通过带有画中画安装程序的命令提示符终端安装 CacheTools 模块。首先,我们必须打开命令提示符终端,然后我们必须在终端内部编写以下 pip 命令:


pip install cachetools

当我们按下回车键时,画中画安装程序将开始通过终端在我们的系统中安装 CacheTools 模块。

如我们所见,Cachetools 模块已经成功安装到我们的系统中,现在我们可以在 Python 程序中调用这个模块,通过 Python 处理我们系统中存在的缓存。

CacheTools 模块:函数

在这里,我们将只讨论 Python 的 Cachetools 模块中存在的函数。这里需要注意的是,这些函数在 Python 中是装饰函数类型,当我们使用这些函数时,它们将在程序中作为装饰函数使用。

下面是 Python CacheTools 模块中的五个函数:

  • 藏起
  • TTLCache
  • rcache
  • 乌克兰语
  • 图片

现在,我们将详细研究上面提到的所有函数,并通过在 Python 程序中使用它们来了解它们的工作原理。

缓存函数

CacheTools 模块的缓存函数在 Python 中用作装饰函数,默认情况下,它在程序中执行简单的缓存。当我们使用缓存装饰器调用一个函数时,它将缓存我们调用的函数,以便以后用作缓存。

语法:

下面是在 Python 程序中使用缓存装饰函数的语法:


@cached(cache = {})
def any_funct():
    pass # Code in the function

参数:在缓存装饰器中,我们使用了一个带有 any_funct()名称的默认函数(我们甚至可以在函数内部给出参数)。在 Python 程序中使用缓存装饰器时,我们将在默认函数中编写逻辑代码,而不是 pass语句。

现在,让我们在 Python 程序中使用这个缓存装饰器来更好地理解它的工作原理以及它如何节省我们的时间。

例 1:

查看下面的程序,了解缓存装饰器的实现:


# Import cached from Cachetools Module
from cachetools import cached 
# Import time module in the program
import time
# Calling a function without using cache
def fiban(n):
    return n if n<2 else fiban(n-1) + fiban(n-2) 
# Calculating total time for performing operation
totalTime1 = time.time()
# Printing function result
print("Result of operation: ", fiban(31)) 
# Total time taken
print("Time Taken by function without cache: ", time.time() - totalTime1)
# Calling function using cache
@cached(cache = {})
def fiban(n): 
    return n if n<2 else fiban(n-1) + fiban(n-2)
# Result of operation performed by function
totalTime2 = time.time()
print("Result of operation: ", fiban(31))
# Now total time taken in Operation
print("Time Taken by function with cached: ", time.time() - totalTime2) 

输出:

Result of operation:  1346269
Time Taken by function without cache:  0.8905675411224365
Result of operation:  1346269
Time Taken by function with cached:  0.015604496002197266

说明:

我们首先从 CacheTools 模块中导入缓存的装饰函数,以便在我们的程序中使用它。我们还在程序中导入了时间模块,以保持对时间的计数,并检查缓存如何使函数调用更快。之后,我们定义了一个默认函数,并使用逻辑代码通过运算来计算值,并在运算后返回值。当我们在这个 fiban()函数中使用一个参数来查找一个实际值时,我们先使用 time()函数,然后再找出执行这个操作需要多少时间。然后,我们打印我们在操作中得到的值以及执行操作所花费的总时间。之后,我们使用了缓存的 decorator 函数,并定义了相同的默认函数,即 fiban()函数,其中包含相同的逻辑。现在,我们再次使用时间函数来计算调用该函数所需的总时间。然后,在 fiban()函数中给定一个参数后,我们打印了操作以及使用缓存装饰器执行操作所花费的总时间。

我们可以在输出中看到,当我们在没有缓存的情况下调用函数时,比使用缓存装饰器调用函数花费的时间要多得多(当两个函数相同时,具有精确的逻辑,并且在调用时具有相同的参数)。这就是缓存装饰器如何通过将函数保存在缓存内存中来帮助我们,并在再次调用时节省大量时间。

TTLCache 函数

TTLCache 也称为“生存时间”缓存,它也是 Cachetools Module 包中包含的装饰函数。当我们在程序中调用一个函数时,它也在系统中的缓存上工作。但是它的工作方式与 Cachetools 模块的前一个函数非常不同,我们可以从这两个函数的语法中看到这一点。

语法:

下面是在 Python 程序中使用 TTLCache 装饰函数的语法:


# Working on cache
@cached(cache = TTLCache(maxsize = 33, ttl = 600))
# Default function
def anyFunct():
    pass # logical code in the function

参数:与缓存装饰器语法不同,我们必须在 TTLCache 装饰器函数中总共给出两个参数。我们还可以看到,在使用函数中的参数之前,我们已经将缓存类型指定为 TTLCache。以下是我们必须在 TTLCache 装饰器中使用的参数:

  1. maxsize:TTLCache 函数内部使用的 maxsize 定义了可以存储在 TTL cache 内部的函数的最大大小。
  2. ttl: 我们在‘TTL’参数中给出的值表示函数的缓存将在系统的缓存内存中存储多长时间。我们在 ttl 参数中给出的值以秒为单位。

现在,让我们在 Python 程序中使用这个 TTLCache 装饰器来理解它的工作原理以及它对我们的用处。

例 2:

查看以下程序,了解 TTLCache 功能的实现:


# Import cached and TTLCACHE from Cachetools Module
from cachetools import cached, TTLCache
# Import time module in the program
import time
# Using the TTLCache decorator
@cached(cache = TTLCache(maxsize = 64, ttl = 90))
# A default function to carry operations
def myFunc(num): 
    # Keeping track on total time taken
    timeTaken = time.time() 
    time.sleep(num) 
    print("nTotal time taken for executing the function: ", time.time() - timeTaken) 
    return (f"I am executed with the function number: {num}")
# Calling the default function twice
print(myFunc(4)) 
print(myFunc(4))
# Using sleep function to create a break
time.sleep(100)
# Calling function after break
print(myFunc(4))

输出:

Total time taken for executing the function:  4.015438556671143
I am executed with the function number: 4
I am executed with the function number: 4

Total time taken for executing the function:  4.015343904495239
I am executed with the function number: 4

说明:

我们已经从程序中的 CacheTools 模块和时间模块中导入了缓存和 TTLCache 装饰器,以记录调用函数所花费的时间。我们使用了 TTLCache 装饰器,定义其参数如下:定义的最大化参数等于 64,存储缓存的总时间等于 90 秒。之后,我们定义了一个默认函数来执行操作,然后我们使用 time()函数来计算调用该函数所需的时间。之后,我们在 print 语句中调用了该函数两次。然后,我们暂停使用 sleep()函数第三次调用该函数。我们使用了 100 秒的休息时间,因为在 TTLCache 函数的参数中,我们给了 90 秒来存储缓存。

我们可以在输出中看到,当我们第二次调用函数时,它是从 TTLCache 装饰器的缓存中调用的。但是当我们暂停时,它再次从程序中调用,因为 TTLCache 不再存储函数的缓存内存。

rcache

RRCache 是随机替换缓存的缩写,顾名思义,RRCache 是一种缓存技术,在这种技术中,函数从缓存内存中的项目中随机选择并丢弃它们。RRCache 函数随机执行此操作,以便在需要时释放缓存内存中的一些空间。

语法:以下是在 Python 程序中使用 RRCache 装饰函数的语法:


# Working on cache
@cached(cache = RRCache(maxsize = 34))
# Default function
def anyFunct():
    pass # logical code in the function   

参数:RRCache 有一个必要的参数,即 maxsize,它与我们在 TTLCache 装饰函数中使用的 maxsize 参数相同。除了这个参数,RRCache 还接受一个可选的“choice 参数”,在程序中默认设置为“random.choice”。

现在,让我们在 Python 程序中使用这个 RRCache 装饰器来理解它的工作原理以及它对我们的用处。

示例 3: 查看以下程序,了解 RRCache 功能的实现:


# Import cached and RRCACHE from Cachetools Module
from cachetools import cached, RRCache
# Import time module in the program
import time
# Using the RRCache decorator
@cached(cache = TTLCache(maxsize = 32))
# A default function to carry operations
def newFunc(m): 
    # Keeping track on total time taken
    timeTaken = time.time()
    time.sleep(m) # Delay in printing result displays task is under process
    print("nTotal time taken for executing the function: ", time.time() - timeTaken)
    return (f"I am executed with the function number: {m}")
# Calling the default function in print statement
print(newFunc(2))
print(newFunc(3))
print(newFunc(1))
print(newFunc(2))
print(newFunc(2))
print(newFunc(4))
print(newFunc(3))
print(newFunc(3))
print(newFunc(2))

输出:

Total time taken for executing the function:  2.01472806930542
I am executed with the function number: 2

Total time taken for executing the function:  3.01532244682312
I am executed with the function number: 3

Total time taken for executing the function:  1.015653133392334
I am executed with the function number: 1
I am executed with the function number: 2
I am executed with the function number: 2

Total time taken for executing the function:  4.003695011138916
I am executed with the function number: 4
I am executed with the function number: 3
I am executed with the function number: 3
I am executed with the function number: 2

说明:

在输出中,我们可以看到 RRCache 装饰器的行为和功能,因为它在任何函数调用时都会随机丢弃缓存,并且很多时候函数是从存储在 RRCache 中的缓存中调用的。

乌克兰语

LRUCache decorator 函数在缓存的 decorator 中使用,就像我们已经了解的另外两个函数一样。LRUCache 代表最近最少使用的缓存,顾名思义,这个装饰函数为程序中最近使用的函数保留缓存。

语法:以下是在 Python 程序中使用 LRUCache 装饰函数的语法:


# Working on cache
@cached(cache = LRUCache(maxsize = 4))
# Cache stored for this Default function 
def anyFunc():
    pass # some logical code will be written here

参数: LRUCache decorator 只取一个参数,即 maxsize,它设置缓存中将存储多少最近调用的函数。

现在,让我们在 Python 程序中使用这个 LRUCache 装饰器来理解它的工作原理以及它对我们的用处。

例 4:

查看以下程序,了解 LRUCache 功能的实现:


# Import cached and LRUCACHE from Cachetools Module
from cachetools import cached, LRUCache
# Import time module in the program
import time
# Using the LRUCache decorator function
@cached(cache = LRUCache(maxsize = 5))
# A default function to carry operations
def newFunc(m): 
    # Keeping track on total time taken
    timeTaken = time.time()
    time.sleep(m) # Delay in printing result displays task is under process
    print("nTotal time taken for calling the default function: ", time.time() - timeTaken)
    return (f"I am executed with the function number: {m}")
# Calling the default function in print statement
print(newFunc(2))
print(newFunc(3))
print(newFunc(1))
print(newFunc(2))
print(newFunc(2))
print(newFunc(4))
print(newFunc(3))

输出:

Total time taken for calling the default function:  2.0151138305664062
I am executed with the function number: 2

Total time taken for calling the default function:  3.015472888946533
I am executed with the function number: 3

Total time taken for calling the default function:  1.0000226497650146
I am executed with the function number: 1
I am executed with the function number: 2
I am executed with the function number: 2

Total time taken for calling the default function:  4.015437841415405
I am executed with the function number: 4
I am executed with the function number: 3

说明:

我们调用的默认函数正好比我们为 LRUCache 函数定义的 maxsize 参数多 2 倍,即 7 倍。这是因为,首先,当函数被调用时,它被存储在 LRUCache 的高速缓冲存储器中,然后,在接下来的 5 次中,函数将从 LRUCache 装饰器中存在的高速缓冲存储器中被调用。但是,这是第七次从程序的内存中调用默认函数,因为现在它超过了我们为 LRUCache 定义的最大大小,即 5。

我们可以看到 LRUCache 装饰器导致的结果变化。

图片

LFUCache 是另一种类型的缓存技术,代表最少使用的缓存,它也在缓存装饰器中被调用。LFUCache 缓存技术用于检索项目或函数在程序中被调用的频率(频率)。在 LFUCache 缓存技术中,程序中调用次数最少的项或函数会从缓存中丢弃,执行此操作是为了释放缓存中的一些空间。

语法:以下是在 Python 程序中使用 LFUCache 装饰函数的语法:


# Working on cache
@cached(cache = LFUCache(maxsize = 5))
# Cache stored for this Default function 
def newFunc():
    pass # some logical code will be written here

参数:lfcache decorator 函数只接受一个参数,即 maxsize,它设置了缓存中将存储多少个调用频率最低的函数。如果一个项或函数参数在 maxsize 中没有被连续调用多次,那么它将从缓存中被丢弃。

现在,让我们在 Python 程序中使用这个 LFUCache 装饰器来理解它的工作原理以及它对我们的用处。

例 5:

查看以下程序,了解 LFUCache 功能的实现:


# Import cached and LFUCACHE from Cachetools Module
from cachetools import cached, LFUCache
# Import time module in the program
import time
# Using the LFUCache decorator function
@cached(cache = LFUCache(maxsize = 5))
# A default function to carry operations
def newFunct(anyNum): 
    # Keeping track on total time taken
    totalTime = time.time()
    time.sleep(anyNum) # Delay in printing result displays task is under process
    print("nTotal time taken for calling the default function: ", time.time() - totalTime)
    return (f"I am executed with the function number: {anyNum}")
# Calling the default function in print statement with number parameters
print(newFunct(2))
print(newFunct(3))
print(newFunct(1))
print(newFunct(2))
print(newFunct(2))
print(newFunct(4))
print(newFunct(1))
print(newFunct(3))
print(newFunct(3))
print(newFunct(2))

输出:

Total time taken for calling the default function:  2.01556396484375
I am executed with the function number: 2

Total time taken for calling the default function:  3.00508451461792
I am executed with the function number: 3

Total time taken for calling the default function:  1.0156123638153076
I am executed with the function number: 1
I am executed with the function number: 2
I am executed with the function number: 2

Total time taken for calling the default function:  4.0026326179504395
I am executed with the function number: 4
I am executed with the function number: 1
I am executed with the function number: 3
I am executed with the function number: 3
I am executed with the function number: 2

说明:

我们已经调用了参数为 3 的默认函数,在此之后,我们连续 5 次没有调用它,这等于 LFUCache 函数中的 maxsize 参数)。因此,LFUCache 将从缓存中丢弃参数为 3 的默认函数,并将从程序的内存中再次调用它。

我们可以看到由于 LFUCache 装饰器导致的结果变化。

结论

在这里,我们已经完成了 CacheTools 模块教程,并了解了 CacheTools 模块中的所有五个函数。我们已经了解了 CacheTools 模块的功能在 Python 程序中是如何工作的,以及如何使用它们来处理程序的缓存。


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。