szcf-weiya / techNotes

My notes about technology.
https://tech.hohoweiya.xyz/
11 stars 7 forks source link

parallel python #1

Open szcf-weiya opened 4 years ago

szcf-weiya commented 3 years ago

starmap

import time
import os
import multiprocessing as mp

def f(i, j = 1):
    t = i + j*0.1
    print(f"pid: {os.getpid()}, sleep {t} secs...")
    time.sleep(t) 

ncpus = 3

ntasks = ncpus

start = time.time()
pool = mp.Pool(ncpus)
pool.starmap(f, [(i, 1) for i in range(ncpus)])
pool.close()
end = time.time()
print(f"time cost: {end - start} secs.")

several tries image image

ntasks = 2*ncpus

start = time.time()
pool = mp.Pool(ncpus)
pool.starmap(f, [(i, 1) for i in range(2*ncpus)])
pool.close()
end = time.time()
print(f"time cost: {end - start} secs.")

image image

szcf-weiya commented 3 years ago

importable target functions

refer to https://pymotw.com/2/multiprocessing/basics.html#importable-target-functions Due to the way the new processes are started, the child process needs to be able to import the script containing the target function. Wrapping the main part of the application in a check for __main__ ensures that it is not run recursively in each child as the module is imported. Another approach is to import the target function from a separate script.

szcf-weiya commented 3 years ago

daemon process and join

szcf-weiya commented 1 year ago

see also: