Skip to content

Instantly share code, notes, and snippets.

@selfboot
Created August 10, 2014 10:01
Show Gist options
  • Save selfboot/99f59f1b4cf8fb8c08eb to your computer and use it in GitHub Desktop.
Save selfboot/99f59f1b4cf8fb8c08eb to your computer and use it in GitHub Desktop.

Revisions

  1. selfboot revised this gist Aug 10, 2014. 1 changed file with 5 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions decorator_cache.py
    Original file line number Diff line number Diff line change
    @@ -41,3 +41,8 @@ def fib_cache(n):

    print t1.timeit(100000)
    print t2.timeit(100000)

    """
    1.71311998367
    0.0279998779297
    """
  2. selfboot created this gist Aug 10, 2014.
    43 changes: 43 additions & 0 deletions decorator_cache.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    #! /usr/bin/env python
    # -*- coding: utf-8 -*-


    from functools import wraps


    def fib_direct(n):
    assert n > 0, 'invalid n'
    if n < 3:
    return n
    else:
    return fib_direct(n - 1) + fib_direct(n - 2)


    def cache(func):
    caches = {}

    @wraps(func)
    def wrap(*args):
    if args not in caches:
    caches[args] = func(*args)

    return caches[args]
    return wrap


    @cache
    def fib_cache(n):
    assert n > 0, 'invalid n'
    if n < 3:
    return 1
    else:
    return fib_cache(n - 1) + fib_cache(n - 2)


    if __name__ == "__main__":
    from timeit import Timer
    t1 = Timer("fib_direct(10)", "from __main__ import fib_direct")
    t2 = Timer("fib_cache(10)", "from __main__ import fib_cache")

    print t1.timeit(100000)
    print t2.timeit(100000)