multithreading - Python: Why is threaded function slower than non thread -


Hello I'm trying to calculate the first 10000 key numbers.

I am doing this for the first time non-threaded and then the calculation was divided between 1 to 5000 and 5001 to 10000. I expected it to be very fast using thread, but the output happens in this way:

  ------ - Result -------- Non Threaded duration: 0.012244000000000005 seconds thread thread: 0.012839000000000017 sec  

There is not really any major difference, except that the threaded function is slightly slower.

This is my code:

  Importing Threading Import from Threading Import Math Thread DF Non-Thread (): PrimeNatom (1,10000) DRF Thread (): T1 = Thread (Target = PrimeNet MM, RGS = (1,5000)) T2 = Thread (Target = PrimeNet MM, RGR = (5001,10000)) T1 Start () T2 Start () Join T1 () t2.join () def is_prime (n): If n% 2 == 0 and n> 2: Returns wrong in True category (3, int (math.sqrt (n) ) If (n & gt; m): For print in range (N, M) i ("should be smaller than n meters"): if (is_prime (i)): l. phen (i) if __name__ == '__main__': Import time print ("-------- non-thread count --------") nTstart_time = time.clock () non-thread () non-threaded time = time.clock () - print nTstart_time ("-------- thread count --------") Tstart_time = time.clock () Threaded () Thread Time = time.clock () - Tstart_time Print ( "-------- Result (" Threaded A Print: "Non-Threaded Period:", Non-Thread Time, "Seconds") Print  

From:

In CPython, Global Interpreter Lock, or GIL, is a Mute X by executing Python Bytecodes at once This lock prevents many original threads Mainly required because CPython's memory management is not thread-safe (although, GIL exists , The other attributes guarantee that it applies.)

It means: Since this is CPU-intensive, and not a python thread, it will give you a This process does not allow multiple bitcodes to run at once, therefore, your threads alternate each other, and the switching overhead that you get in the form of additional time.


Comments

Popular posts from this blog

import - Python ImportError: No module named wmi -

Editing Python Class in Shell and SQLAlchemy -

c# - MySQL Parameterized Select Query joining tables issue -