我想计算pi。程序很简单:
迭代次数越多,计算就越准确。
为了做得快,我使用多处理库。但多处理代码永远不会完成。问题是什么?
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)
答案 0 :(得分:-1)
我在mac上测试了相同的代码。 它运作得很好。
0.25用于多工艺,0.45用于单工艺。
只需更改
[N/process_num for x in range(process_num)]
要
[int(N/process_num for x in range(process_num)]
答案 1 :(得分:-1)
自我回答。
问题是需要关闭流程。
所以我只添加一行。
if __name__ == "__main__":
比我的代码工作!
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)