1
1
#!/usr/bin/env python
2
2
3
- from functools import lru_cache
3
+ from functools import cache , lru_cache
4
4
5
5
6
6
def memoize (f ):
@@ -30,24 +30,32 @@ def fib_lru_cache(n):
30
30
return fib_lru_cache (n - 1 ) + fib_lru_cache (n - 2 )
31
31
32
32
33
+ @cache
34
+ def fib_cache (n ):
35
+ if n < 2 :
36
+ return 1
37
+ else :
38
+ return fib_cache (n - 1 ) + fib_cache (n - 2 )
39
+
40
+
33
41
def fib (n ):
34
42
if n < 2 :
35
43
return 1
36
44
else :
37
45
return fib (n - 1 ) + fib (n - 2 )
38
46
39
47
40
- def execute (func , n_max ):
48
+ def execute (func , n_max , verbose = False ):
41
49
values = []
42
50
start = datetime .now ()
43
51
for n in range (n_max ):
44
52
values .append (func (n ))
45
53
delta = datetime .now () - start
46
- for n in range ( n_max ) :
47
- print ( '{0}({1}) = {2}' . format ( func . __name__ , n , values [ n ]))
48
- delta_time = float ( delta . seconds ) + 1.0e-6 * float ( delta . microseconds )
49
- print ( '{0}: {1:.6f} s' . format ( func . __name__ , delta_time ) )
50
- return delta_time
54
+ if verbose :
55
+ for n in range ( n_max ):
56
+ print ( '{0}({1}) = {2}' . format ( func . __name__ , n , values [ n ]) )
57
+ return float ( delta . seconds ) + 1.0e-6 * float ( delta . microseconds )
58
+
51
59
52
60
if __name__ == '__main__' :
53
61
from argparse import ArgumentParser
@@ -56,10 +64,9 @@ def execute(func, n_max):
56
64
arg_parser = ArgumentParser (description = 'compare memoized versus '
57
65
'non-memooized' )
58
66
arg_parser .add_argument ('n_max' , type = int , help = 'maximum n value' )
67
+ arg_parser .add_argument ('--verbose' , action = 'store_true' ,
68
+ help = 'display computed values' )
59
69
options = arg_parser .parse_args ()
60
- delta_fib = execute (fib , options .n_max )
61
- delta_fib_memoized = execute (fib_memoized , options .n_max )
62
- delta_fib_lru_cache = execute (fib_lru_cache , options .n_max )
63
- print ('non-memoized:\t \t {0:.6f} s' .format (delta_fib ))
64
- print ('memoized:\t \t {0:.6f} s' .format (delta_fib_memoized ))
65
- print ('lru_cache:\t \t {0:.6f} s' .format (delta_fib_lru_cache ))
70
+ for fib_impl in (fib , fib_memoized , fib_cache , fib_lru_cache ):
71
+ delta_time = execute (fib_impl , options .n_max , options .verbose )
72
+ print (f'{ fib_impl .__name__ :20s} : { delta_time :.6f} s' )
0 commit comments