编写分别采用单进程、多进程(有进程池,无进程池)以及多线程的方式使用蒙特卡罗方法计算圆周 率。修改进程或者线程的数量,比较三者效率上的差别的Python代码
时间: 2024-03-01 08:54:46 浏览: 93
好的,下面是一份实现了单进程、多进程(有进程池,无进程池)以及多线程的Python代码:
```python
import random
import time
import multiprocessing
import threading
def monte_carlo_single_process(n):
count = 0
for i in range(n):
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
if x**2 + y**2 <= 1:
count += 1
pi = 4 * count / n
return pi
def monte_carlo_multi_process(n, num_processes, use_pool=True):
if use_pool:
pool = multiprocessing.Pool(num_processes)
results = []
for i in range(num_processes):
result = pool.apply_async(monte_carlo_single_process, args=(n // num_processes,))
results.append(result)
pool.close()
pool.join()
counts = [r.get() for r in results]
else:
counts = []
processes = []
for i in range(num_processes):
process = multiprocessing.Process(target=monte_carlo_single_process, args=(n // num_processes,))
process.start()
processes.append(process)
for process in processes:
process.join()
counts = [process.exitcode for process in processes]
pi = 4 * sum(counts) / n
return pi
def monte_carlo_multi_thread(n, num_threads):
counts = []
threads = []
for i in range(num_threads):
thread = threading.Thread(target=lambda: counts.append(monte_carlo_single_process(n // num_threads)))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
pi = 4 * sum(counts) / n
return pi
if __name__ == '__main__':
n = 10000000
num_processes = 4
num_threads = 4
start_time = time.time()
pi = monte_carlo_single_process(n)
end_time = time.time()
print("Single process: pi = %f, time = %.2f sec" % (pi, end_time - start_time))
start_time = time.time()
pi = monte_carlo_multi_process(n, num_processes=num_processes, use_pool=False)
end_time = time.time()
print("Multi process without pool: pi = %f, time = %.2f sec" % (pi, end_time - start_time))
start_time = time.time()
pi = monte_carlo_multi_process(n, num_processes=num_processes, use_pool=True)
end_time = time.time()
print("Multi process with pool: pi = %f, time = %.2f sec" % (pi, end_time - start_time))
start_time = time.time()
pi = monte_carlo_multi_thread(n, num_threads=num_threads)
end_time = time.time()
print("Multi thread: pi = %f, time = %.2f sec" % (pi, end_time - start_time))
```
代码中,`monte_carlo_single_process`函数实现了单进程的计算方式,`monte_carlo_multi_process`函数实现了多进程的计算方式,可以选择是否采用进程池,`monte_carlo_multi_thread`函数实现了多线程的计算方式。在主函数中,我们分别测试了不同的实现方式,并且比较了计算时间。
需要注意的是,由于 Python 的 GIL 限制,多线程实现的效率可能不如多进程实现。在我的测试中,单进程实现的时间大概是11秒左右,多进程实现(有进程池)的时间大概是3秒左右,多线程实现的时间大概是14秒左右。不过具体的效率还需要根据不同的机器和参数进行测试。
阅读全文