103-Multi-process efficiency

103-Multi-process efficiency

There is no multi-process, even if the CPU has multiple cores, the program only runs on one core, and multi-process cannot be used to improve efficiency. For 50 million additions, if it takes 2.5 seconds, it takes 5 seconds to call it twice.

import time

def calc():
    result = 0
    for i in range(1, 50000001):
        result += i
    print(result)

if __name__ =='__main__':
    start = time.time()
    calc()
    calc()
    end = time.time()
    print(end-start)

Through multiple processes, the program runs on multiple cores, and the same call twice 50 million addition operations, the time is only half.

import time
import os

def calc():
    result = 0
    for i in range(1, 50000001):
        result += i
    print(result)

if __name__ =='__main__':
    start = time.time()
    for i in range(2):
        pid = os.fork()
        if not pid:
            calc()
            exit()
    os.waitpid(-1, 0) # Suspend the parent process and continue to execute downwards until the end of the child process
    os.waitpid(-1, 0) # Each waitpid can only handle one zombie process, and two child processes need to be called twice
    end = time.time()
    print(end-start)
Reference: https://cloud.tencent.com/developer/article/1334513 103-The efficiency of multi-processes- Cloud+Community- Tencent Cloud