by fxtentacle · 6y ago · 0 comments
That's the reason why you need to go multi-process if you want to reach a similar level of concurrency in Python as multi-thread in C++. And that surely adds a lot of complexity.
As a very practical example of this, TensorFlow has a dedicated page with advice on how to make the Python part that reads the files from disk less slow. Think about that: The bottleneck for training a highly advanced AI with millions of parameters is in the 20 lines of Python code to read in a binary file...
I had a funny such experience lately in a job interview. I told the interviewer his misconception could be falsified with ~10 LOC summing a list with 2 threads.
If any operations were GIL-bound (which is extremely common, even if not intentional, by reliance on bytecode instructions dealing with CPython API under the hood, like attribute lookups or iteration special methods), then execution is probably interleaved serially and constrained by the interpreter’s GIL allocation, and slower than just summing serially.
I’ve seen a lot of people who are cocksure they know some contrarian “actually you can use threads” trivia about Python and just naively use the threading module or naively use the newish ThreadPoolExecutor stuff not realizing that no, in fact, it’s not somehow magically always GIL-avoiding to do so.
# main.py
import random
from concurrent.futures import ThreadPoolExecutor as Pool
items = [random.random() for _ in range(10 ** 7)]
def run(items, n):
step = len(items) // n
with Pool(max_workers=n) as ex:
res = [ex.submit(sum, items[i*step : (i+1)*step]) for i in range(n)]
return sum(r.result() for r in res)
if __name__ == '__main__':
import timeit
import sys
n = sys.argv[1] if len(sys.argv) > 1 else 1
time = timeit.timeit('run(items, %s)' % n, 'from __main__ import run, items', number=10)
print("%s\t%.3f" % (n, time / 10))
$ for x in `seq 1 16` ; do python3 -m main $x ; done
1 0.172
2 0.170
3 0.166
4 0.155
5 0.149
6 0.142
7 0.144
8 0.140
9 0.136
10 0.135
11 0.135
12 0.137
13 0.135
14 0.136
15 0.136
16 0.136(2) You're not measuring what you think you are measuring.
Take out the Pool altogether:
def run(items, n):
step = len(items) // n
res = [sum(items[i*step : (i+1)*step]) for i in range(n)]
return sum(r for r in res)
and the results are similar: 1 0.170
2 0.170
3 0.147
4 0.145
5 0.142
6 0.142
7 0.138
8 0.137
9 0.135
10 0.138
I have some guesses why it improves, but I'm not certain. It's definitely nothing to do with multithreading.EDIT: As an aside, you can speed this up 20x by using Numpy:
items = numpy.array([random.random() for _ in range(10 ** 7)])
def run(items, n):
return numpy.sum(items)
1 0.007
Supporting the original point that running code in low-level languages produces amazing speedups vs fancy parallelism methods.I think it does that pretty well but, well, that's just like my opinion.
I’m pretty sure the time “savings” you are seeing here come from somewhere else. At a first glance, your copying the huge list while submitting it to the thread pool, this has overhead. Maybe lots of smaller copies are faster on your machine.
I imagine Python works roughly the same.
Parallelism is possible, but only for computations in native code.
FWIW Node.js is essentially the same situation.
Been a while since I've used Python, but as far as I remember the GIL only affects Python objects. So if you use Numpy for operations, you can avoid the GIL.
Correct.
Threads cannot help Python-heavy code; they can help I/O-heavy or native-heavy code (assuming native code releases the GIL).
Even without multithreading, numpy programming can give amazing speedups. It's the reason why data science Python isn't dead in the water.
Spawn a thread and handle disk or socket IO requests there? You can get fancy and use a thread pool so maybe 15 lines of code.
Not sure why you used the word “supposedly”. Threads have been in the standard library for a very long time.
Yes and still run the risk of running into GIL problems. You claim to have shown 10 lines to an interviewer that proved he was wrong about the GIL still being an issue and I've yet to see an example of it not being one when using pure python. Yes there are certain cases where you don't hit the GIL, no that doesn't mean it isn't still an issue when dealing with threads.
I had multiple of those experiences. Even then people wouldn’t believe me so we had to look at Python C code and read about threads and IO operations in C and such. The other alternative is to write a deliberately slow socket server that takes say 5 seconds to respond then then write a threaded client to issue requests and seeing how they complete in parallel.
There are a lot of ways to handle the IO intensive scenario in python:
* Threading - Works with python libraries written in C, but now you need to add locks to your code to prevent race conditions. Not good for CPU heavy work because it’s switching context every ~100 instructions.
* Gevent - Requires minimal code changes, but it usually blocks when running code from python libraries written in C. This uses event loop style concurrency and automatically patches internal python libraries to switch context when IO occurs. This means less time spent unnecessarily switching context, so it can scale better than python’s threading.
* multiprocessing - Better for CPU intensive work, but requires more memory than other solutions. You don’t need to worry about race conditions since the processes are separate.
* asyncio - Requires code changes and using compatible libraries. It does event loop style concurrency that allows you to specify specifically when to switch context. Like with gevent, this means less time spent unnecessarily switching context.
* ...And there are probably a bunch of other ways I’m missing.
I’ve heard that this sort of stuff is simpler in Go.
https://erikengbrecht.blogspot.com/2008/06/what-does-io-boun...
The hard part is always that you have more data than can fit into memory, and need complex prefetch solutions to parallelize getting the next batch of data while one batch’s numerical linear algebra computation is in progress.
Many libraries handle this transparently for the user in an extension module, such as Keras & PyTorch.
I think it’s misleading to act incredulous that this is the bottleneck ... it doesn’t have anything to do with Python, GIL, etc. (and there are easy-to-maintain solutions for this in Python).
This person was actively arguing with me about what it was. It's one of many battle stories for why I pretty much just assume everyone on reddit is stupid unless shown otherwise.