Python のメモリ内キャッシュと有効期限 質問する

Python のメモリ内キャッシュと有効期限 質問する

同じプロセスを実行する複数のスレッドがあり、今後 n 秒間は作業を行わないことを互いに通知できる必要がありますが、通知されても世界が終わるわけではありません。

私の目標は、文字列と TTL をキャッシュに渡し、キャッシュ内にあるすべての文字列をリストとして取得できるようにすることです。キャッシュはメモリ内に存在でき、TTL は 20 秒以内になります。

これを実現する方法について何か提案はありますか?

ベストアンサー1

サードパーティのライブラリを使用しない場合は、コストのかかる関数にもう 1 つのパラメータを追加できます: ttl_hash=None。この新しいパラメータはいわゆる「時間依存ハッシュ」で、 に影響を与えることだけが目的ですlru_cache

例えば:

from functools import lru_cache
import time


@lru_cache()
def my_expensive_function(a, b, ttl_hash=None):
    del ttl_hash  # to emphasize we don't use it and to shut pylint up
    return a + b  # horrible CPU load...


def get_ttl_hash(seconds=3600):
    """Return the same value withing `seconds` time period"""
    return round(time.time() / seconds)


# somewhere in your code...
res = my_expensive_function(2, 2, ttl_hash=get_ttl_hash())
# cache will be updated once in an hour

おすすめ記事