Advertisement
user_137

Fibs Faster

Apr 21st, 2014
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. from numba import jit
  2.  
  3.  
  4. def ifib(x):
  5.     fibn = 0
  6.     fibo = 1
  7.     for i in xrange(1, x):
  8.         fibo, fibn = fibo+fibn, fibo
  9.     return fibo
  10.  
  11.  
  12. def makemem():
  13.     memo = {1: 0, 2: 1}
  14.  
  15.     def imem(x):
  16.         if x in memo:
  17.             return memo[x]
  18.         m = len(memo)
  19.         fibo = memo[m]
  20.         fibn = memo[m-1]
  21.         for i in xrange(m, x+1):
  22.             fibo, fibn = fibo+fibn, fibo
  23.             memo[i] = fibo
  24.         return fibo
  25.  
  26.     return imem
  27.  
  28.  
  29. @jit
  30. def jfib(x):
  31.     fibn = 0
  32.     fibo = 1
  33.     for i in xrange(1, x):
  34.         fibnn = fibo
  35.         fibo = fibo+fibn
  36.         fibn = fibnn
  37.     return fibo
  38.  
  39.  
  40. def fastFib(x, memo):
  41.     assert type(x) == int and x >= 0 and type(memo) == dict
  42.     if x == 1 or x == 2:
  43.         return 1
  44.     if x in memo:
  45.         return memo[x]
  46.     memo[x] = fastFib(x-1, memo) + fastFib(x-2, memo)
  47.     return memo[x]
  48.  
  49.  
  50. def fib(x):
  51.     assert type(x) == int and x >= 0
  52.     if x == 1 or x == 2:
  53.         return 1
  54.     else:
  55.         return fib(x-1) + fib(x-2)
  56.  
  57.  
  58.  
  59.  
  60. """                                            
  61.  
  62. from memoization import *
  63.  
  64. f = makemem()  # prepare memoized version
  65.  
  66. %time fib(30)
  67. CPU times: user 531 ms, sys: 75 ms, total: 606 ms
  68. Wall time: 512 ms
  69. Out[4]: 832040
  70.  
  71. %time fastFib(30, {})
  72. CPU times: user 0 ns, sys: 0 ns, total: 0 ns
  73. Wall time: 62.9 µs
  74. Out[5]: 832040
  75.  
  76. %time ifib(30)
  77. CPU times: user 8 µs, sys: 0 ns, total: 8 µs
  78. Wall time: 12.2 µs
  79. Out[6]: 832040
  80.  
  81. %time f(30)
  82. CPU times: user 24 µs, sys: 1 µs, total: 25 µs
  83. Wall time: 33.1 µs
  84. Out[7]: 832040
  85.  
  86. %time jfib(30)
  87. CPU times: user 47.2 ms, sys: 5.09 ms, total: 52.3 ms
  88. Wall time: 47.3 ms
  89. Out[8]: 832040L
  90.  
  91. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement