vegaseat

using high performance time.perf_counter() to time functions

Mar 13th, 2015
430
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. ''' str_count_sub_timing_hperf.py
  2. timing functions that count the number of sub_strings in a string
  3. using high performance time.perf_counter()
  4. new in Python 3.3 and higher
  5. '''
  6.  
  7. import time
  8. import re
  9.  
  10. def count_tony(text, sub):
  11.     return sum(text[n:].startswith(sub)
  12.            for n in range(len(text) - len(sub) + 1))
  13.  
  14. def count_snip(text, sub):
  15.     return len(re.findall(r'(?={})'.format(sub), text))
  16.  
  17. def count_snee(text, sub, start=0):
  18.     count = 0
  19.     while True:
  20.         ix = text.find(sub, start)
  21.         if ix < 0: break
  22.         start = ix + 1
  23.         count += 1
  24.     return count
  25.  
  26. text = "this person assesses your performance"
  27. sub = "sses"
  28.  
  29. # returned value is in fractional seconds
  30. start = time.perf_counter()
  31. result1 = count_tony(text, sub)
  32. end = time.perf_counter()
  33.  
  34. elapsed = end - start
  35. print("count_tony('{}', '{}') = {}".format(text, sub, result1))
  36. print("elapsed time = {:0.6f} micro_seconds".format(elapsed*1000000))
  37.  
  38. start2 = time.perf_counter()
  39. result2 = count_snee(text, sub)
  40. end2 = time.perf_counter()
  41.  
  42. elapsed2 = end2 - start2
  43. print("count_snee('{}', '{}') = {}".format(text, sub, result2))
  44. print("elapsed time = {:0.6f} micro_seconds".format(elapsed2*1000000))
  45.  
  46. start3 = time.perf_counter()
  47. result3 = count_snip(text, sub)
  48. end3 = time.perf_counter()
  49.  
  50. elapsed3 = end3 - start3
  51. print("count_snip('{}', '{}') = {}".format(text, sub, result3))
  52. print("elapsed time = {:0.6f} micro_seconds".format(elapsed3*1000000))
  53.  
  54. ''' result (Python 3.4.1 64bit)-->
  55. count_tony('this person assesses your performance', 'sses') = 2
  56. elapsed time = 38.228700 micro_seconds
  57.  
  58. count_snee('this person assesses your performance', 'sses') = 2
  59. elapsed time = 5.119915 micro_seconds
  60.  
  61. count_snip('this person assesses your performance', 'sses') = 2
  62. elapsed time = 130.387175 micro_seconds
  63.  
  64. '''
Advertisement
Add Comment
Please, Sign In to add comment