Timing a Function (Python)

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
vegaseat vegaseat is offline Offline Aug 23rd, 2005, 1:20 am |
0
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.
Quick reply to this message  
Python Syntax
  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. """
0
vegaseat vegaseat is offline Offline | Dec 17th, 2005
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).
 
0
bumsfeld bumsfeld is offline Offline | Feb 4th, 2007
Vegaseat, to keep primes from going over n, replace line
s = range(3, n+2, 2)
with
s = range(3, n+1, 2)

Henri
 
0
vegaseat vegaseat is offline Offline | Feb 5th, 2007
Oh thanks Henri, I corrected this oversight.
 
 

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC