参考:https://zhuanlan.zhihu.com/p/93305921
现在的笔记本电脑,台式机都流行多核心,低频率的架构,原因是低频率低耗电,而多核心又可以在并行计算中表现出色。
多进程 vs. 多线程
多进程 (Multi-Process) 和多线程 (Multi-Thread) 最大的区别是,多进程是在各自单独的进程内存管理下运行代码,而多线程是共享一个进程内存。在各自单独的进程管理下,多进程的明显优势是可以最大的利用计算机多核心的处理能力。但是多进程也有其劣势,比如说在进程之间通信需要 IPC (Inter Process Communication) 工具,而不像多线程那样可以共享内存数据。
Pool使用CPU多核
import multiprocessing
import random
import time
# worker
def worker(name):
t = 0
for i in range(2):
print(name + " " + str(i))
x = random.randint(1, 3)
t += x
time.sleep(t * 0.1)
return {name:t}
if __name__ == '__main__':
num_cores = int(multiprocessing.cpu_count())
pool = multiprocessing.Pool(num_cores)
# input processes
jobs = []
for i in range(10):
jobs.append(pool.apply_async(worker, args=(str(i))))
results = [p.get() for p in jobs]
print(results)
输出结果
0 0
0 1
1 0
1 1
2 0
2 1
3 0
3 1
4 0
4 1
5 0
5 1
6 0
6 1
7 0
7 1
8 0
8 1
9 0
9 1
[{'0': 5}, {'1': 3}, {'2': 3}, {'3': 4}, {'4': 4}, {'5': 3}, {'6': 3}, {'7': 3}, {'8': 3}, {'9': 4}]
或者使用map方式
if multi_num > 1:
pool = Pool(processes=multi_num)
pool.map(worker, list_idx)
pool.close()
pool.join()