As a curious performance engineer we always want to find out the fastest method and implement/advise the same to get the maximum performance.

In python we can see multiple ways of running the same piece of code depends on how it is being written and which of the following ( Asyncio / MultiThreading / MultiProcessing / Sync ) is being used.

As an experiment i have written a very small IO bound code and have implemented Asyncio / MultiThreading / MultiProcessing / Sync one by another see the performance.

Let's begin here -

In experiment we will call the https://httpbin.org/uuid and extract the UUID from the response. Basically when we call this link it provides following response -

{
  "uuid": "58caefcd-ee43-4cf3-84a6-dff6a434468e"
}

We will do the same in code and implement multiple iteration (50).

1. Sync

#Python 3.7.7
import requests, time

def fetch(url):

    with requests.session().get(url) as response:
        print(response.json()['uuid'])

if __name__ ==  '__main__':
    url = '<https://httpbin.org/uuid>'
    ts = time.time()
    for _ in range(50):
        fetch(url)
    te = time.time()
    print(' Time taken: {} '.format(te-ts))

Output

C:\\Users\\< dir path >\\Temp>python ex_sync.py
50c42995-1bf5-4714-800f-2f8f2955c19c
73573554-66e0-4047-8035-811df8477396
. . . . . . .
c8250526-563a-4f72-a83b-ec25719bc23c`
bc97ab52-05b6-4f70-86a9-b8830db6dbec
**Time taken: 41.848782539367676**

Overall time taken for the above code is 41.85 seconds.

How sync code works: Sequential

Sync code works in sequential or linear fashion one task after another. No overlapping of any task. And it only leverage 1 core of the CPU.

2. Multiprocessing

multiprocessing module allows the programmer to fully leverage multiple processors (Cores of CPU) on a given machine. Lets understand the above with below image - for example, an array of 6 task, in quad core machine, multiprocessor can use all the cores as demonstrated in image.