In [1]:
import numpy as np
from numpy import sqrt
from random import uniform
from time import time
import multiprocessing
import matplotlib.pyplot as plt
%matplotlib
number_of_darts = 10**np.arange(1,7)
number_of_darts.tolist()
Out[1]:
In [8]:
def pi_approx_serial(number_of_darts):
''' approximate pi using serial method'''
number_of_darts_in_circle = 0
start_time = time()
for n in xrange(number_of_darts):
x = uniform(0,1)
y = uniform(0,1)
distance = np.sqrt((x-0.5)**2+(y-0.5)**2)
if distance <= 0.5:
number_of_darts_in_circle += 1
else:
pass
end_time = time()
execution_time = end_time - start_time
pi_apx = 4*number_of_darts_in_circle/float(number_of_darts)
return [execution_time, pi_apx]
time_serial = []
for dart in number_of_darts:
time_temp = pi_approx_serial(dart)
time_temp.insert(0, dart)
time_serial.append(time_temp)
time_serial = np.array(time_serial)
time_serial
Out[8]:
In [2]:
def pi_approx(number_of_darts):
''' approximate pi using MC method'''
number_of_darts_in_circle = 0
for n in xrange(number_of_darts):
x = uniform(0,1)
y = uniform(0,1)
distance = sqrt((x-0.5)**2+(y-0.5)**2)
if distance <= 0.5:
number_of_darts_in_circle += 1
else:
pass
return 4*number_of_darts_in_circle/float(number_of_darts)
In [14]:
from IPython import parallel
rc = parallel.Client()
dview = rc[:]
with dview.sync_imports():
from numpy import sqrt
from random import uniform
from time import time
def pi_approx_par(number_of_darts):
''' approximate pi using parallel method '''
number_of_darts_per_thread = number_of_darts/len(dview)
start_time = time()
d_result = dview.apply_async(pi_approx, number_of_darts_per_thread)
result = d_result.get()
end_time = time()
execution_time = end_time - start_time
pi_apx = sum(result)/float(len(result))
return [execution_time, pi_apx]
time_Ipar = []
for darts in number_of_darts:
time_temp = pi_approx_par(darts)
time_temp.insert(0, darts)
time_Ipar.append(time_temp)
time_Ipar = np.array(time_Ipar)
time_Ipar
Out[14]:
In [6]:
def pi_approx_stdlib(number_of_darts):
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=2)
start_time = time()
pi_apx = pool.apply_async(pi_approx, [number_of_darts]).get()
end_time = time()
execution_time = end_time-start_time
pool.terminate()
return [execution_time, pi_apx]
time_stdlib = []
for dart in number_of_darts:
time_temp = pi_approx_stdlib(dart)
time_temp.insert(0, dart)
time_stdlib.append(time_temp)
time_stdlib = np.array(time_stdlib)
time_stdlib
Out[6]:
In [18]:
f0, ax0 = plt.subplots()
ax0.loglog(time_serial[:,0], time_serial[:,1], label='serial')
ax0.loglog(time_Ipar[:,0], time_Ipar[:,1], label='Ipython')
ax0.loglog(time_stdlib[:,0],time_stdlib[:,1], label='StdLib')
ax0.legend()
ax0.
Out[18]:
In [ ]: