Monday, 13 January 2020

python multiprocessing

#pycharm

import time
import multiprocessing

start = time.perf_counter()

def do_something(seconds):
    print(f'Sleep {seconds} second...')
    time.sleep(seconds)
    print('Done sleeping')

processes = []

if __name__ ==  '__main__':

    for _ in range(10):
        p = multiprocessing.Process(target=do_something, args=[1.5])
        p.start()
        processes.append(p)

    for process in processes:
        process.join()

    finish = time.perf_counter()

    print(f'finish in {round(finish-start, 3)} seconds')

------------------------------
#logs

PS C:\Users\bob\python_multiprocessing> python app.py
Sleep 1 second...
Sleep 1 second...
Sleep 1 second...
Sleep 1 second...
Sleep 1 second...
Sleep 1 second...
Sleep 1 second...
Sleep 1 second...
Sleep 1 second...
Sleep 1 second...
Done sleeping
Done sleeping
Done sleeping
Done sleeping
Done sleeping
Done sleeping
Done sleeping
Done sleeping
Done sleeping
Done sleeping
finish in 1.221 seconds

reference:
https://www.youtube.com/watch?v=fKl2JW_qrso
https://stackoverflow.com/questions/18204782/runtimeerror-on-windows-trying-python-multiprocessing

No comments:

Post a Comment