Guest User

Untitled

a guest
Apr 17th, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import multiprocessing
  4. import threading
  5. import time
  6. import random
  7.  
  8. def hello(thid, n):
  9.     i = 0
  10.     res = 0
  11.     while i < n:
  12.         res += i
  13.         i += 1
  14.     print("%d. result: %d"%(thid, res))
  15.  
  16. def test_process(n):
  17.     tlist = []
  18.     for i in range(4):
  19.         t = multiprocessing.Process(target=hello, args=(i,n,))
  20.         t.start()
  21.         tlist.append(t)
  22.  
  23.     for t in tlist:
  24.         t.join()
  25.  
  26. def test_thread(n):
  27.     tlist = []
  28.     for i in range(4):
  29.         t = threading.Thread(target=hello, args=(i,n,))
  30.         t.start()
  31.         tlist.append(t)
  32.  
  33.     for t in tlist:
  34.         t.join()
  35.  
  36. def test_sima(n):
  37.     for i in range(4):
  38.         hello(i,n)
  39.  
  40. if __name__ == '__main__':
  41.     n = 3000*1000
  42.     s = time.time()
  43.     test_thread(n)
  44.     print("Multi-Thread: %.3fs" % (time.time() - s))
  45.  
  46.     s = time.time()
  47.     test_process(n)
  48.     print("Multi-Process: %.3fs" % (time.time() - s))
  49.  
  50.     s = time.time()
  51.     test_sima(n)
  52.     print("Single: %.3fs" % (time.time() - s))
  53.  
  54.     print("Done!")
Advertisement
Add Comment
Please, Sign In to add comment