Ticket #21351: speedtest.py

File speedtest.py, 1.5 KB (added by Bouke Haarsma, 11 years ago)
Line 
1import timeit
2import sys
3
4memoize_setup = """
5from django.utils.functional import memoize
6def fib(n):
7 if n < 2:
8 return n
9 return fib(n-1) + fib(n-2)
10_fib = {}
11fib = memoize(fib, _fib, 1)
12fib(100)
13"""
14lru_cache_setup = """
15from django.utils.lru_cache import lru_cache
16@lru_cache(maxsize=None)
17def fib(n):
18 if n < 2:
19 return n
20 return fib(n-1) + fib(n-2)
21fib(100)
22"""
23
24# read performance -- the cache is warmed up, so read a single entry
25read_loop = """
26fib(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.
32memoize_write_loop = """
33_fib.clear()
34fib(100)
35"""
36lru_cache_write_loop = """
37fib.cache_clear()
38fib(100)
39"""
40
41
42memoize_read_time = timeit.timeit(read_loop, memoize_setup, number=10 ** 6)
43lru_cache_read_time = timeit.timeit(read_loop, lru_cache_setup, number=10 ** 6)
44memoize_write_time = timeit.timeit(memoize_write_loop, memoize_setup,
45 number=10 ** 4)
46lru_cache_write_time = timeit.timeit(lru_cache_write_loop, lru_cache_setup,
47 number=10 ** 4)
48
49print("""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))
Back to Top