I want to calculate pi. The procedure is simple:
The more iterations, the more accurate the calculation.
For doing fast, I use multiprocessing library. But the multiprocessing code never finishes. What's the problem?
import timeit
start = timeit.default_timer()
import random
from multiprocessing import Pool
N = 1000000
process_num = 4
def make_pi(end):
count_inbound = 0
for x in range(end):
the_x = random.random()
the_y = random.random()
if((the_x**2 + the_y**2) <= 1):
count_inbound += 1
return count_inbound
# Multiprocessing.
p = Pool(processes = process_num)
count_in = p.map(make_pi, [N/process_num for x in range(process_num)])
print(4*sum(count_in)/N)
# Normal.
##print(4*make_pi(N)/N)
stop = timeit.default_timer()
print(stop - start)
Self answer.
the problem is process need to be closed.
so i add just one line.
if __name__ == "__main__":
than my code do work!
import timeit
start = timeit.default_timer()
import random
from multiprocessing import Pool
N = 1000000
process_num = 4
def make_pi(end):
count_inbound = 0
for x in range(end):
the_x = random.random()
the_y = random.random()
if((the_x**2 + the_y**2) <= 1):
count_inbound += 1
return count_inbound
if __name__ == "__main__":
#multiprocessing code
p = Pool(processes = process_num)
count_in = p.map(make_pi, [int(N/process_num) for x in range(process_num)])
print(4*sum(count_in)/N)
#normal code
#print(4*make_pi(N)/N)
stop = timeit.default_timer()
print(stop - start)