Coders Packet

Python program to convert Celsius to Fahrenheit using Pool class of multiprocessing module

By Yuvraj Singh

In this tutorial, we are going to convert Celsius to Fahrenheit using the pool class of multiprocessing module in python.

What is multiprocessing:

Multiprocessing is a system that has more than one or two processors. In Multiprocessing, CPUs are added for increasing computing speed of the system. Because of Multiprocessing, There are many processes are executed simultaneously. Process creation is a time-consuming process. Every process owned a separate address space.

 

What is pool class:

The Pool class represents a pool of worker processes. It has methods which allows tasks to be offloaded to the worker processes in a few different ways.

It creates multiple Python processes in the background and spreads out your computations for you across multiple CPU cores so that they all happen in parallel without you needing to do anything. we can even set the number of processes you want to be working at once.

We can use different methods like map, startmap(like map but with multiple arguments), apply etc.

 

How to convert Celsius to Fahrenheit:

Fahrenheit = (Celsius * 1.8) + 32

 

CODE:

Using python built-in map method(function):

# sequential time

import time
import os
from timeit import default_timer as timer
from multiprocessing import Pool, cpu_count


# calculate fahrenheit
def fahrenheit(celsius):
    time.sleep(1)
    print("child process id:", os.getpid())
    return (celsius * 1.8) + 32

def main():

    start = timer()

    print(f'starting computations on {cpu_count()} cores')
    celsius = (37, 45, 30, 20, 10, 35, 25, 33, 29)
    print("parent process id:", os.getpid())
    res = list(map(fahrenheit, celsius))
    print(res)
    end = timer()
    print(f'elapsed time: {end - start}')


if __name__ == '__main__':
    main()

Using map method(function) of Pool Class:

# multiprocessing time (parallel time)

import time
import os
from timeit import default_timer as timer
from multiprocessing import Pool, cpu_count

# calculate fahrenheit
def fahrenheit(celsius):
    time.sleep(1)
    print("child process id:", os.getpid())
    return (celsius * 1.8) + 32


def main():

      start = timer()

    print(f'starting computations on {cpu_count()} cores')

    celsius = (37, 45, 30, 20, 10, 35, 25, 33, 29)

    print("parent process id:", os.getpid())
    with Pool() as pool:
    res = pool.map(fahrenheit, celsius)
    print(res)

    end = timer()
    print(f'elapsed time: {end - start}s')
if __name__ == '__main__':
    main()

Download project

Reviews Report

Submitted by Yuvraj Singh (yuvrajeyes)

Download packets of source code on Coders Packet