Advertisement
here2share

# threading4_timeit.py

Dec 5th, 2019
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.21 KB | None | 0 0
  1. # threading4_timeit.py
  2.  
  3. import time
  4. import threading
  5.  
  6. def func(name, n):
  7.     '''show the millisecond name and count'''
  8.     start = time.clock()
  9.     for k in range(1, n+1):
  10.         t = str(time.clock()-start)
  11.         t = float(t[:t.index('.')+7])
  12.         p.append([t, "{} count {}".format(name, k)])
  13.    
  14. def background(f):
  15.     '''
  16.     a threading decorator
  17.     use @background above the function you want to run in the background
  18.     '''
  19.     def bg_f(*a, **kw):
  20.         threading.Thread(target=f, args=a, kwargs=kw).start()
  21.     return bg_f
  22. @background
  23. def counter_one(name, n):
  24.     func(name, n)
  25.        
  26. def counter_two(name, n):
  27.     func(name, n)
  28.  
  29. # start the counters
  30. # note that with the @background decorator
  31.  
  32. result = []
  33. p = []
  34. start = time.clock()
  35. counter_one("A", 500)
  36. counter_one("B", 500)
  37. counter_one("C", 500)
  38. counter_one("D", 500)
  39. t = [(float(str(time.clock()-start)[:9]),'threading')]
  40. p.sort()
  41. for z in p: print '{:.7f} \t {}'.format(z[0],z[1])
  42. print
  43.  
  44. p = []
  45. start = time.clock()
  46. counter_two("Z", 2000)
  47. t += [(float(str(time.clock()-start)[:9]),'linear')]
  48. for z in p: print '{:.7f} \t {}'.format(z[0],z[1])
  49. t.sort()
  50. a,b = t
  51. a,a2 = a
  52. b,b2 = b
  53. print
  54. print 'At {}s, {} is {}x faster than {} which took {}s'.format(a,a2,str(b/a)[:6],b2,b)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement