LoginSignup
0
0

More than 3 years have passed since last update.

functools.lru_cacheとmemoize

Last updated at Posted at 2020-06-23

memoize

計算結果を保存しておくことができ、次回呼び出す時にその結果を利用することができますので早くなります。

memoize.py
def memoize(f):
    memo = {}
    def _wrapper(n):
        if n not in memo:
            memo[n] = f(n)
            print('hit')
            print(memo)
        return memo[n]
    return _wrapper


@memoize
def long_func(n):
    r = 0
    for i in range(10000000000):
        r += n * i
        return r


for i in range(10):
    print(long_func(i))
    #long_func(i)


print('next run')
for i in range(10):
    print(long_func(i))
    #long_func(i)

functools.lru_cache

上と同じことができます

lru_cache.py
import functools


@functools.lru_cache()
def long_func(n):
    r = 0
    for i in range(10000000000):
        r += n * i
        return r


for i in range(10):
    print(long_func(i))

print(long_func.cache_info())
# long_func.cache_clear()  キャッシュをクリア
print('next run')
for i in range(10):
    print(long_func(i))

print(long_func.cache_info())
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0