可以做些什么来加速这个memoization装饰器?

Ger*_*rat 3 python memoization

我想要的是一个memoization装饰器:

我已经调整了一个我看到的例子并想出了以下内容:

import functools

class Memoized(object):
  """Decorator that caches a function's return value each time it is called.
  If called later with the same arguments, the cached value is returned, and
  not re-evaluated.
  """

  __cache = {}

  def __init__(self, func):
    self.func = func
    self.key = (func.__module__, func.__name__)

  def __call__(self, *args):
    try:
      return Memoized.__cache[self.key][args]
    except KeyError:
      value = self.func(*args)
      Memoized.__cache[self.key] = {args : value}
      return value
    except TypeError:
      # uncachable -- for instance, passing a list as an argument.
      # Better to not cache than to blow up entirely.
      return self.func(*args)

  def __get__(self, obj, objtype):
    """Support instance methods."""
    return functools.partial(self.__call__, obj)

  @staticmethod
  def reset():
    Memoized.__cache = {}
Run Code Online (Sandbox Code Playgroud)

我的问题是缓存部分似乎涉及很多开销(例如,用于递归函数).使用以下函数作为示例,我可以使用非memoized版本调用fib(30)十次,其时间比memoized版本少.

def fib(n):

   if n in (0, 1):
      return n
   return fib(n-1) + fib(n-2)
Run Code Online (Sandbox Code Playgroud)

谁能建议一个更好的方法来编写这个装饰器?(或指向一个更好(即更快)的装饰器,做我想要的).我对保留方法签名或帮助内省工具"了解"有关装饰函数的任何内容不感兴趣.

谢谢.

PS使用python 2.7

Gle*_*ard 13

您实际上并未缓存任何数据,因为每次设置新的缓存值都会覆盖前一个:

Memoized.__cache[self.key] = {args : value}
Run Code Online (Sandbox Code Playgroud)

例如.

import functools

class Memoized(object):
    """Decorator that caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned, and
    not re-evaluated.
    """

    cache = {}

    def __init__(self, func):
        self.func = func
        self.key = (func.__module__, func.__name__)
        self.cache[self.key] = {}

    def __call__(self, *args):
      try:
          return Memoized.cache[self.key][args]
      except KeyError:
          value = self.func(*args)
          Memoized.cache[self.key][args] = value
          return value
      except TypeError:
          # uncachable -- for instance, passing a list as an argument.
          # Better to not cache than to blow up entirely.
          return self.func(*args)

    def __get__(self, obj, objtype):
        """Support instance methods."""
        return functools.partial(self.__call__, obj)

    @staticmethod
    def reset():
        Memoized.cache = {}
Run Code Online (Sandbox Code Playgroud)
  • fib(30)没有缓存:2.86742401123
  • fib(30)与缓存:0.000198125839233

其他一些说明:

  • 不要用__prefix; 没有理由在这里,它只是丑化了代码.
  • 而不是使用单个,单一的类属性dict,给Memoized它自己的dict的每个实例,并保持Memoized对象的注册表.这改善了封装,并消除了取决于模块和功能名称的奇怪性.

.

import functools
import weakref

class Memoized(object):
    """Decorator that caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned, and
    not re-evaluated.

    >>> counter = 0
    >>> @Memoized
    ... def count():
    ...     global counter
    ...     counter += 1
    ...     return counter

    >>> counter = 0
    >>> Memoized.reset()
    >>> count()
    1
    >>> count()
    1
    >>> Memoized.reset()
    >>> count()
    2

    >>> class test(object):
    ...     @Memoized
    ...     def func(self):
    ...         global counter
    ...         counter += 1
    ...         return counter
    >>> testobject = test()
    >>> counter = 0
    >>> testobject.func()
    1
    >>> testobject.func()
    1
    >>> Memoized.reset()
    >>> testobject.func()
    2
    """

    caches = weakref.WeakSet()

    def __init__(self, func):
        self.func = func
        self.cache = {}
        Memoized.caches.add(self)

    def __call__(self, *args):
      try:
          return self.cache[args]
      except KeyError:
          value = self.func(*args)
          self.cache[args] = value
          return value
      except TypeError:
          # uncachable -- for instance, passing a list as an argument.
          # Better to not cache than to blow up entirely.
          return self.func(*args)

    def __get__(self, obj, objtype):
        """Support instance methods."""
        return functools.partial(self.__call__, obj)

    @staticmethod
    def reset():
        for memo in Memoized.caches:
            memo.cache = {}

if __name__ == '__main__':
    import doctest
    doctest.testmod()
Run Code Online (Sandbox Code Playgroud)

编辑:添加测试,并使用weakref.WeakSet.请注意,WeakSet仅适用于2.7(OP正在使用); 对于在2.6中工作的版本,请参阅编辑历史记录.