Multi-threaded execution speed for Python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.