DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Python (http://www.daniweb.com/forums/forum114.html)
-   -   Code Snippet: Timing a Function (Python) (http://www.daniweb.com/forums/thread216610.html)

vegaseat Aug 23rd, 2005 1:20 am
Timing a Function (Python)
 
Python24 introduces the function decorator that lends itself nicely to the timing of a function. As a sample function we are using the ever popular and rather stodgy prime number generator. The prime number generator seems to exist only to fluster students and to make niggling comparisons of the speed of computer languages.

  1. # time a function using time.time() and the a @ function decorator
  2. # tested with Python24 vegaseat 21aug2005
  3.  
  4. import time
  5.  
  6. def print_timing(func):
  7. def wrapper(*arg):
  8. t1 = time.time()
  9. res = func(*arg)
  10. t2 = time.time()
  11. print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0)
  12. return res
  13. return wrapper
  14.  
  15. # declare the @ decorator just before the function, invokes print_timing()
  16. @print_timing
  17. def getPrimeList(n):
  18. """ returns a list of prime numbers from 2 to < n using a sieve algorithm"""
  19. if n < 2: return []
  20. if n == 2: return [2]
  21. # do only odd numbers starting at 3
  22. s = range(3, n+1, 2)
  23. # n**0.5 may be slightly faster than math.sqrt(n)
  24. mroot = n ** 0.5
  25. half = len(s)
  26. i = 0
  27. m = 3
  28. while m <= mroot:
  29. if s[i]:
  30. j = (m*m-3)//2
  31. s[j] = 0
  32. while j < half:
  33. s[j] = 0
  34. j += m
  35. i = i+1
  36. m = 2*i+3
  37. return [2]+[x for x in s if x]
  38.  
  39. if __name__ == "__main__":
  40. print "prime numbers from 2 to <10,000,000 using a sieve algorithm"
  41. primeList = getPrimeList(10000000)
  42. time.sleep(2.5)
  43.  
  44. """
  45. my output -->
  46. prime numbers from 2 to <10,000,000 using a sieve algorithm
  47. getPrimeList took 4750.000 ms
  48. """
vegaseat Dec 17th, 2005 2:08 am
Note: If you have Windows, it is better to use the time.clock() function (updates 1000 times per second) rather than time.time() (updates 18.2 times per second).

bumsfeld Feb 4th, 2007 12:57 pm
Vegaseat, to keep primes from going over n, replace line
s = range(3, n+2, 2)
with
s = range(3, n+1, 2)

Henri

vegaseat Feb 5th, 2007 12:21 am
Oh thanks Henri, I corrected this oversight.


All times are GMT -4. The time now is 10:35 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC