Let's say I have this sample code:
x = foo1(something1)
y = foo2(something2)
z = max(x, y)
I want to improve the execution time of this code by using threads (hope it helps isn't it?). I'd like to keep things as simple as possible so basically what I'd like to do is creating two threads working at the same time which compute respectively foo1
and foo2
.
I'm reading something about threads but I found it a little tricky and I can't lose too much time in it just for doing such a simple thing.
Read the documentation here first to understand the code below:
You can use python
thread
module or the newThreading
module, however usingthread
module is simpler in syntax,will output,
Read more from here, Python - Multithreaded Programming
Assuming
foo1
orfoo2
is CPU-bound, threading doesn't improve the execution time... in fact, it normally makes it worse... for more information, see David Beazley's PyCon2010 presentation on the Global Interpreter Lock / Pycon2010 GIL slides. This presentation is very informative, I highly recommend it to anyone trying to distribute load across CPU cores.The best way to improve performance is with the multiprocessing module
Assuming there is no shared state required between
foo1()
andfoo2()
, do this to improve execution performance...From my machine, this results in:
It won't help. Read the Python FAQ.