1 | import timeit
|
---|
2 | import sys
|
---|
3 |
|
---|
4 | memoize_setup = """
|
---|
5 | from django.utils.functional import memoize
|
---|
6 | def fib(n):
|
---|
7 | if n < 2:
|
---|
8 | return n
|
---|
9 | return fib(n-1) + fib(n-2)
|
---|
10 | _fib = {}
|
---|
11 | fib = memoize(fib, _fib, 1)
|
---|
12 | fib(100)
|
---|
13 | """
|
---|
14 | lru_cache_setup = """
|
---|
15 | from django.utils.lru_cache import lru_cache
|
---|
16 | @lru_cache(maxsize=None)
|
---|
17 | def fib(n):
|
---|
18 | if n < 2:
|
---|
19 | return n
|
---|
20 | return fib(n-1) + fib(n-2)
|
---|
21 | fib(100)
|
---|
22 | """
|
---|
23 |
|
---|
24 | # read performance -- the cache is warmed up, so read a single entry
|
---|
25 | read_loop = """
|
---|
26 | fib(50)
|
---|
27 | """
|
---|
28 |
|
---|
29 | # write performance -- write 100 items per run, not one item per run to have
|
---|
30 | # the cache contain multiple entries, not just one which might skew the
|
---|
31 | # results.
|
---|
32 | memoize_write_loop = """
|
---|
33 | _fib.clear()
|
---|
34 | fib(100)
|
---|
35 | """
|
---|
36 | lru_cache_write_loop = """
|
---|
37 | fib.cache_clear()
|
---|
38 | fib(100)
|
---|
39 | """
|
---|
40 |
|
---|
41 |
|
---|
42 | memoize_read_time = timeit.timeit(read_loop, memoize_setup, number=10 ** 6)
|
---|
43 | lru_cache_read_time = timeit.timeit(read_loop, lru_cache_setup, number=10 ** 6)
|
---|
44 | memoize_write_time = timeit.timeit(memoize_write_loop, memoize_setup,
|
---|
45 | number=10 ** 4)
|
---|
46 | lru_cache_write_time = timeit.timeit(lru_cache_write_loop, lru_cache_setup,
|
---|
47 | number=10 ** 4)
|
---|
48 |
|
---|
49 | print("""Python: %s
|
---|
50 | +-----------+----------+-----------+
|
---|
51 | | | memoize | lru_cache |
|
---|
52 | +-----------+----------+-----------+
|
---|
53 | | 1M reads | %000.5fs | %000.5fs |
|
---|
54 | | 1M writes | %000.5fs | %000.5fs |
|
---|
55 | +-----------+----------+-----------+""" % (
|
---|
56 | sys.version,
|
---|
57 | memoize_read_time,
|
---|
58 | lru_cache_read_time,
|
---|
59 | memoize_write_time,
|
---|
60 | lru_cache_write_time
|
---|
61 | ))
|
---|