Process is a system concept , It also corresponds to CPU The underlying hardware concept of .
First , You can check your CPU Can support several threads :
from multiprocessing import cpu_count
print(cpu_count())
When starting multiple processes , It's better not to approach or surpass CPU The number of hardware processes for .
from multiprocessing import Process
from time import sleep
def run(n):
sleep(n)
print(n)
if __name__ == '__main__':
p1 = Process(target=run, args=(1,))
p2 = Process(target=run, args=(2,))
p3 = Process(target=run, args=(3,))
p4 = Process(target=run, args=(4,))
p1.start()
p2.start()
p3.start()
p4.start()
Multi process startup is very convenient , Start to specify the target function name and input parameters ( Notice here that there's a comma ).
Multiprocessing through to CPU The clever use of multicore , Parallel computing can accelerate the program to a certain extent , Look at the experiment 2:
from multiprocessing import Process
from time import time
def run():
start = time()
res = 0
for i in range(10000):
for j in range(10000):
res += 1
res -= 1
print('time cost:', time() - start)
if __name__ == '__main__':
t0 = time()
run()
p1 = Process(target=run, args=())
p2 = Process(target=run, args=())
p3 = Process(target=run, args=())
p4 = Process(target=run, args=())
p1.start()
p2.start()
p3.start()
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()
print('all time cost:', time() - t0)
This experiment compares the running time of multi process with that of multi process . Output is :
time cost: 3.343838691711426
time cost: 3.4023547172546387
time cost: 3.4059526920318604
time cost: 3.4068567752838135
time cost: 3.409113883972168
all time cost: 6.755127668380737
You can see , use 4 Processes completed 4 Computing times and not opening multiple processes to complete 1 The time of calculation is almost the same .