Friday, March 31, 2017

Best practices while using multiprocessing in Python

As we know that python threads can't explore the true parallel processing because of GIL. So to achieve the same we often use multiprocessing.
While using multiprocessing, one of the best practices is to pass the cpu affinity. It will be useful in below scenarios:
Example:
There is a four core processor and we are running 4 python processes. So here we can utilise all the four core available. Down side of not using cpu affinity is that processor will keep scheduling the processes among available core causing additional context switching overhead. Suppose we have allocated different core to all the four processes resulting no context switching and leading a better throughput.
Please be thoughtful when using the same, otherwise you could end up restricting the core for a given process.

Python code sample to demonstrate the cpu affinity
---------------------------------------------------------------------------

>>> import psutil
>>> psutil.cpu_count()
4
>>> p = psutil.Process()
>>> # get
>>> p.cpu_affinity()
[0, 1, 2, 3]
>>> # set; from now on, process will run on CPU #0 and #1 only
>>> p.cpu_affinity([0, 1])
>>> p.cpu_affinity()
[0, 1]
>>> # reset affinity against all eligible CPUs
>>> p.cpu_affinity([])

No comments:

Post a Comment