Advertisement
here2share

# heavy_multiprocessing.py

Apr 4th, 2021
839
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. # heavy_multiprocessing.py
  2.  
  3. import multiprocessing as mp
  4. from random import random as rnd
  5. import time
  6.  
  7.  
  8. def my_function(i, param1, param2, param3):
  9.     result = 0
  10.     for z in range(5000000):
  11.         result += param1 ** 2 * param2 + param3
  12.     return (i, result)
  13.  
  14.  
  15. def get_result(result):
  16.     global results
  17.     results.append(result)
  18.  
  19.  
  20. if __name__ == '__main__':
  21.     params = [[(rnd()) for i in range(10)] for j in range(3)]
  22.     results = []
  23.     ts = time.time()
  24.     for i in range(0, len(params[0])):
  25.         get_result(my_function(i, params[0][i], params[1][i], params[2][i]))
  26.     print('Time in serial:', time.time() - ts)
  27.     print(results)
  28.     print
  29.     results = []
  30.     ts = time.time()
  31.     pool = mp.Pool(mp.cpu_count())
  32.     for i in range(0, len(params[0])):
  33.         pool.apply_async(my_function, args=(i, params[0][i], params[1][i], params[2][i]), callback=get_result)
  34.     pool.close()
  35.     pool.join()
  36.     print('Time in parallel:', time.time() - ts)
  37.     print(results)
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement