Python multithreading is a bit of a chicken, the application of the scene is limited, multiple cores per unit of time can only run a single thread.
There is a pool, four pumps, but only one person, one can only open the management of one of them, so four pumps are useless. However, if the pump's operating time and cooling recovery time is 1:3 (thanks to Inoahx, it has been changed), then the utilization of the configuration is as high as 100%.
Run code directly single.py
#!/usr/bin/python3#-*-coding:utf-8-*-#Author:zhouchao#function: Run program calculation time directlyImportThreadingImportSYSImportMathImporttimelists= []; forXinchRange (1,10000000): Lists.append (x); length=len (lists); forXinchRange (600): Step= Math.ceil (float (length)/600) Minindex= Step *xifMinindex + Step >Length:maxindex=lengthElse: Maxindex= minindex+StepPrint(Lists[minindex:maxindex]) datetime= Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ()) FileObject= Open ("Time1.txt",'A +'); Fileobject.write (str (datetime)+"\ n"); Fileobject.close ();
Time Required: 134 s
Open 600 threads to run the same code
multithread.py
#!/usr/bin/python3#-*-coding:utf-8-*-#Author:zhouchao#function: 600 thread compute Execution TimeImportThreadingImportSYSImportMathImporttimelists= []; forXinchRange (1,10000000): Lists.append (x);deffunction (i):GlobalLists length=len (lists); Step= Math.ceil (float (length)/600) Minindex= Step *IifMinindex + Step >Length:maxindex=lengthElse: Maxindex= minindex+StepPrint(Lists[minindex:maxindex]) datetime= Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ())#datetime = str (Lists[minindex:maxindex])FileObject = open ("Time2.txt",'A +'); Fileobject.write (str (datetime)+"\ n"); Fileobject.close (); Threads= [] forIinchRange (600): T= Threading. Thread (Target=function, args=(i,)) Threads.append (t) T.start () T.join ()
Time Required: s
Multithreaded execution speed for Python