Advertisement
here2share

# threading2vs4_timeit.py

Dec 5th, 2019
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. # threading2vs4_timeit.py
  2.  
  3. import time
  4. import threading
  5.  
  6. def background(f):
  7.     '''
  8.     a threading decorator
  9.     use @background above the function you want to run in the background
  10.     '''
  11.     def bg_f(*a, **kw):
  12.         threading.Thread(target=f, args=a, kwargs=kw).start()
  13.     return bg_f
  14. @background
  15. def counter(name, n):
  16.     '''show the millisecond name and count'''
  17.     start = time.clock()
  18.     for k in range(1, n+1):
  19.         t = str(time.clock()-start)
  20.         t = float(t[:t.index('.')+7])
  21.         p.append([t, "{} count {}".format(name, k)])
  22.  
  23. # start the counters
  24. # note that with the @background decorator
  25.  
  26. p = []
  27. start = time.clock()
  28. for z in range(2):
  29.     counter("%d of 2 Threads "%(z+1), 500)
  30. t = [(float(str(time.clock()-start)[:9]),'spooling 2')]
  31. p.sort()
  32. for z in p: print '{:.7f} \t {}'.format(z[0],z[1])
  33. print
  34.  
  35. p = []
  36. start = time.clock()
  37. for z in range(4):
  38.     counter("%s of 4 Threads "%(z+1), 250)
  39. t += [(float(str(time.clock()-start)[:9]),'spooling 4')]
  40. for z in p: print '{:.7f} \t {}'.format(z[0],z[1])
  41. t.sort()
  42. a,b = t
  43. a,a2 = a
  44. b,b2 = b
  45. print
  46. 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