fibonacci.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. """
  2. Downloaded from https://code.google.com/p/benchrun/
  3. Fibonacci numbers test benchmark
  4. """
  5. from benchrun import Benchmark, clock
  6. def fib1(n):
  7. if n < 2:
  8. return n
  9. return fib1(n-1) + fib1(n-2)
  10. def fib2(n):
  11. if n < 2:
  12. return n
  13. a, b = 1, 0
  14. for i in xrange(n-1):
  15. a, b = a+b, a
  16. return a
  17. class FibonacciBenchmark(Benchmark):
  18. """Compare time to compute the nth Fibonacci number recursively
  19. (fib1) and iteratively (fib2)."""
  20. # Execute for all combinations of these parameters
  21. parameters = ['version', 'n']
  22. version = ['fib1', 'fib2']
  23. n = range(0, 60, 5)
  24. # Compare timings against this parameter value
  25. reference = ('version', 'fib1')
  26. def run(self, n, version):
  27. f = globals()[version]
  28. # Don't repeat when slow
  29. if version == 'fib1' and n > 10:
  30. # Skip altogether
  31. if n > 30:
  32. return None
  33. t1 = clock()
  34. f(n)
  35. t2 = clock()
  36. return t2-t1
  37. # Need to repeat many times to get accurate timings for small n
  38. else:
  39. t1 = clock()
  40. f(n); f(n); f(n); f(n); f(n); f(n); f(n)
  41. f(n); f(n); f(n); f(n); f(n); f(n); f(n)
  42. t2 = clock()
  43. return (t2 - t1) / 14
  44. if __name__ == '__main__':
  45. FibonacciBenchmark().print_result()