944,134 Members | Top Members by Rank

Ad:
  • Python Code Snippet
  • Views: 46061
  • Python RSS
0

Timing a Function (Python)

by on Aug 23rd, 2005
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.
Python Code Snippet (Toggle Plain Text)
  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. """
Comments on this Code Snippet
Dec 17th, 2005
0

Re: Timing a Function (Python)

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).
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Feb 4th, 2007
0

Re: Timing a Function (Python)

Vegaseat, to keep primes from going over n, replace line
s = range(3, n+2, 2)
with
s = range(3, n+1, 2)

Henri
Nearly a Posting Virtuoso
bumsfeld is offline Offline
1,422 posts
since Jul 2005
Feb 5th, 2007
0

Re: Timing a Function (Python)

Oh thanks Henri, I corrected this oversight.
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Message:
Previous Thread in Python Forum Timeline: Percentage of one list in another.
Next Thread in Python Forum Timeline: Can't get grid to work!





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC