Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # threading4_timeit.py
- import time
- import threading
- def func(name, n):
- '''show the millisecond name and count'''
- start = time.clock()
- for k in range(1, n+1):
- t = str(time.clock()-start)
- t = float(t[:t.index('.')+7])
- p.append([t, "{} count {}".format(name, k)])
- def background(f):
- '''
- a threading decorator
- use @background above the function you want to run in the background
- '''
- def bg_f(*a, **kw):
- threading.Thread(target=f, args=a, kwargs=kw).start()
- return bg_f
- @background
- def counter_one(name, n):
- func(name, n)
- def counter_two(name, n):
- func(name, n)
- # start the counters
- # note that with the @background decorator
- result = []
- p = []
- start = time.clock()
- counter_one("A", 500)
- counter_one("B", 500)
- counter_one("C", 500)
- counter_one("D", 500)
- t = [(float(str(time.clock()-start)[:9]),'threading')]
- p.sort()
- for z in p: print '{:.7f} \t {}'.format(z[0],z[1])
- print
- p = []
- start = time.clock()
- counter_two("Z", 2000)
- t += [(float(str(time.clock()-start)[:9]),'linear')]
- for z in p: print '{:.7f} \t {}'.format(z[0],z[1])
- t.sort()
- a,b = t
- a,a2 = a
- b,b2 = b
- print
- 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