Why CPU cores perform differently with the same task under multiprocessing?

51 views Asked by At

When I run the following code on a Linux machine with 12 CPU cores, where 2 cores were saved for overhead or system function and 10 cores were consumed to run exactly the same task (a simple factorial calculation) simultaneously. And the result shows that, all cores are started at the almost same time since print function in stress_test() comes at almost the same time, BUT the same calculation takes significantyly different time to finish. What could have caused this? (lack of knowledge in Computer Science, really appreciate the help) Thanks in advance!

from multiprocessing import Pool, cpu_count
from datetime import datetime

def stress_test(args):
    cpu, value = args
    start_time = datetime.now()
    print(f'cpu starts: {cpu}')
    for i in range(value):
        value = value * i
    print(f"cpu: {cpu} time: {datetime.now() - start_time}")

if __name__ == '__main__':
    start_time = datetime.now()
    cpu_count = cpu_count() - 2
    with Pool(cpu_count) as mp_pool:
        mp_pool.map(stress_test, [(cpu, int(2e8)) for cpu in range(cpu_count)])
    print(f"total: {datetime.now() - start_time}")

print result

run the code in Python 3.7.5 on a Ubuntu machine, expected the similar time consumption for the same factorial calculation under multiprocessing

0

There are 0 answers