[Tutor] memoize, lookup, or KIS?

Albert-Jan Roskam fomcl at yahoo.com
Mon Nov 19 17:52:28 CET 2012


>Presumably the place where you read about them would have listed some
>example decorators that you can use for memoisation. Here's a quick
>example that works for hashable inputs:
>


Some of these I don't really understand so I am hesitant to use them.


>def memo(func):
>    table = {}
>    def wrapper(inputarg):
>        try:
>            return table[inputarg]
>        except KeyError:
>            table[inputarg] = val = func(inputarg)
>            return val
>    return wrapper
>
>@memo
>def square(x):
>    print('Calling square()')
>    return x ** 2


Nice and conscise! I did some profiling and it is fast, too. But as Steven said, I also need to maximize the cache, among other things. I also gotta figure out what I'll do with datetime values (probably it's not useful to cache these).


# 1M function calls
a--115.837 CPU seconds  # no memoization
b--215.753 CPU seconds  # memodict # http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/
c--62.547 CPU seconds   # simple decorator # http://code.activestate.com/recipes/577219-minimalistic-memoization/
d--60.771 CPU seconds   # Oscar Benjamin, modified to:
    def memo(func):
        table = {}
        def wrapper(*inputarg):
            try:
                return table[inputarg[0:2]] #
            except KeyError:
                table[inputarg[0:2]] = val = func(*inputarg)
                return val
        return wrapper


More information about the Tutor mailing list