5

例如,我有:

def readDb():
    # Fetch a lot of data from db, spends a lot time
    ...
    return aList

def calculation():
    x = readdb()
    # Process x
    ...
    return y

在python解释器中,
每次运行calculation()都需要很长时间重新读取数据库,这是不必要的。
如何存储结果readdb()以避免这种还原过程?

编辑:
我在这里发现了一个类似的问题,但我不太清楚答案
保存函数以便在不重新执行的情况下重复使用

4

3 回答 3

6
def readDb():
    ... #Fetch a lot of data from db, spends a lot time
    return aList

def calculation(data):
    x=data
    ...process x...
    return y

data = readDb()

calculation(data)
calculation(data)
calculation(data)

这只会命中数据库一次。

基本上,您希望将 readDb() 的结果保存到一个单独的变量中,然后您可以将其传递给calculation()。

于 2013-03-19T15:56:55.123 回答
5

写一个简单的装饰器:

class memo(object):
    def __init__(self, fun):
        self.fun = fun
        self.res = None
    def __call__(self):
        if self.res is None:
            self.res = self.fun()
        return self.res

@memo
def readDb():
    # ... etc
    return aList

有关更通用的解决方案,请查看此处:http ://code.activestate.com/recipes/498245-lru-and-lfu-cache-decorators/ 。

于 2013-03-19T15:58:30.980 回答
1

现代 Python 的更新答案

对于仍在寻找如何执行此操作的任何人,标准库functools包含一个装饰器函数@functools.lru_cache来执行此操作。

例如(来自文档):

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

这将存储最后一次32调用get_pep,当使用相同的参数调用它时,将返回缓存的值。

于 2018-08-17T11:00:32.237 回答