fork download
  1. import math
  2. import multiprocessing as m
  3. import time
  4.  
  5. threadCount = 8
  6. maxNum = 10 ** 7
  7.  
  8. startTime = time.time()
  9. total = 0
  10.  
  11. result_list = []
  12. def log_results(result):
  13. result_list.append(result)
  14.  
  15. def calculate(start, end):
  16. temp = 0
  17. for d in range(start, end):
  18. temp = temp + (1/d) ** 2
  19. return temp
  20.  
  21. if __name__ == '__main__':
  22. pool = m.Pool()
  23. for threads in range(0, threadCount):
  24. pool.apply_async(calculate, args = (round(maxNum/threadCount*threads)+1, round(maxNum/threadCount*(threads+1)),), callback = log_results)
  25. pool.close()
  26. pool.join()
  27.  
  28. total = sum(result_list)
  29.  
  30. print("\nFinished in " + str(round(time.time() - startTime)) + " seconds")
  31. print("Pi: " + str(math.sqrt(total * 6)))
Success #stdin #stdout 4.83s 42152KB
stdin
Standard input is empty
stdout
Finished in 5 seconds
Pi: 3.141592558095943