Use the multiprocessing package to parallelize the computation in the problem below.

Use the multiprocessing package to parallelize the computation in the problem below. Upload your parallel function and any other function you might have implemented.

import multiprocessing as mp
import numpy as np
import time

def f(x):
    return np.sqrt(x)+np.sin(x)

def midpoint_integrate():
    a = 0.
    b = 4.
    n = 1000000
    h = (b-a)/n
    
    x = a+h/2.
    s = 0
    for i in range(n):
        s += f(x)
        x += h
    return h*s

def midpoint_integrate_parallel():
    pass


Nprocesses = 10

if __name__ == '__main__':
    # Serial 
    start = time.time()
    print("result  (serial): ", midpoint_integrate())
    stop = time.time()
    print("runtime (serial): ", (stop-start))

    # Parallel 
    pool = mp.Pool(Nprocesses)
    start = time.time()
    print("result  (parallel): ", midpoint_integrate_parallel())
    stop = time.time()
    print("runtime (parallel): ", (stop-start))
    pool.close()

Answers 0

Related Articles