python开多进程 | XYZ
Post

python开多进程

python开多进程

多进程一键开启

使用 multiprocessing

经典方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os
import time
from multiprocessing import Pool

def long_time_task(name):
    print(f'Run Task {name} {os.getpid()}...')
    start = time.time()
    time.sleep(1)
    end = time.time()
    print(f'Task {name} Run {(end - start):.2f} seconds.')
    return name

if __name__ == '__main__':
    t_one = time.time()
    print(f'Parent process {os.getpid()}.')
    p = Pool(34)
    for i in range(34):
        p.apply_async(long_time_task, args=(i,))
    print('waiting for all subprocesses done...')
    p.close()
    p.join()
    t_two = time.time()
    print(f'All subprocesses done. {t_two - t_one:.2f} seconds.')

进程池的进程数选用

  • 可以填入 multiprocessing.cpu_count()
  • IO密集型选用 multiprocessing.cpu_count() + nn 根据情况自选。
  • CPU密集型可直接选用 multiprocessing.cpu_count()

使用 tqdm

更简便的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from tqdm.contrib.concurrent import process_map
import os
import time

def long_time_task(name, sign):
    print(f'Run Task {name} {sign} ({os.getpid()})...')
    start = time.time()
    time.sleep(1)
    end = time.time()
    print(f'Task {name} Run {(end - start):.2f} seconds.')
    return name

if __name__ == '__main__':
    def _generator(m):
        for i in range(m):
            yield "my love"

    r = process_map(long_time_task, range(112), _generator(112), max_workers=34)
    print(multiprocessing.cpu_count())
    print(r)

特点

  • 写法更简便,具有进度条功能。
  • 入参需要将参数生成写在内部(传生成器进去)。
This post is licensed under CC BY 4.0 by the author.