Parallel for loops in Python
Parallelizing a loop means scaling all processes in parallel using multiple cores. When we have a large number of jobs, each computation does not wait for the previous computation in parallel to finish. Instead, it is done using different processors.
In this article, we will parallelize for
a loop in Python.
multiprocessing
Parallelizing for
loops
in Python using the module
To parallelize the loop, we can use the package in Python multiprocessing
, as it supports the creation of subprocesses at the request of another ongoing process.
You can use multiprocessing
the module instead of for loop to perform operations on each element of iterable object. You can use multiprocessing.pool()
the object because using multithreading in Python does not give better results because of the global interpreter lock.
For example,
import multiprocessing
def sumall(value):
return sum(range(1, value + 1))
pool_obj = multiprocessing.Pool()
answer = pool_obj.map(sumall, range(0, 5))
print(answer)
Output:
0, 1, 3, 6, 10
joblib
Parallelizing for
loops
in Python using the module
joblib
The module uses multiprocessing to run multiple CPU cores to perform for
parallelization of loops. It provides a lightweight pipeline that memorizes patterns for simple and straightforward parallel computation.
To perform parallel processing, we have to set the number of jobs, which is limited by the number of cores in the CPU or the number of cores that are currently available or idle.
delayed()
Functions allow us to tell Python to call a specific mentioned method after some time.
Parallel()
The function creates a parallel instance with the specified cores (2 in this case).
We need to create a list for the execution of the code. Then pass the list to parallel, which develops two threads in parallel and distributes the list of tasks to them.
Please refer to the code below.
from joblib import Parallel, delayed
import math
def sqrt_func(i, j):
time.sleep(1)
return math.sqrt(i ** j)
Parallel(n_jobs=2)(delayed(sqrt_func)(i, j) for i in range(5) for j in range(2))
Output:
[1.0,
0.0,
1.0,
1.0,
1.0,
1.4142135623730951,
1.0,
1.7320508075688772,
1.0,
2.0]
asyncio
Parallelizing for
loops
in Python using the module
asyncio
The module is single-threaded and runs the event loop by temporarily suspending the coroutine using the yield from
or methods.await
The code below will execute in parallel when called without affecting the main function to wait. The loop also runs in parallel with the main function.
import asyncio
import time
def background(f):
def wrapped(*args, **kwargs):
return asyncio.get_event_loop().run_in_executor(None, f, *args, **kwargs)
return wrapped
@background
def your_function(argument):
time.sleep(2)
print("function finished for " + str(argument))
for i in range(10):
your_function(i)
print("loop finished")
Output:
ended execution for 4
ended execution for 8
ended execution for 0
ended execution for 3
ended execution for 6
ended execution for 2
ended execution for 5
ended execution for 7
ended execution for 9
ended execution for 1
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
How to convert an integer to bytes
Publish Date:2025/05/08 Views:77 Category:Python
-
Converting an integer int to a byte bytes is the inverse of bytes converting a byte to an integer . Most of the to methods int described in this article are the inverse of the to methods. int bytes bytes int Generic method for converting in
How to convert bytes to int in Python
Publish Date:2025/05/08 Views:111 Category:Python
-
Bytes The data type has a numerical range of 0~255 (0x00~0xFF). A byte has 8 bits of data, that's why its maximum value is 0xFF. In some cases, you need to convert a byte or byte array to an integer for further data processing. Let's see ho
How to Remove Punctuation from a String in Python
Publish Date:2025/05/08 Views:190 Category:Python
-
This tutorial discussed methods for removing punctuation from strings in Python. This is a particularly useful step when preprocessing and cleaning text data for NLP. string Remove punctuation from a string in Python using class methods We
How to Convert an Integer to a String in Python
Publish Date:2025/05/08 Views:69 Category:Python
-
This article will show you different ways to convert an integer to a string using Python code, such as str() the function and the f format method. str() Convert integer to string in Python using function We can use the inbuilt function in P
How to Replace Multiple Characters in a String in Python
Publish Date:2025/05/08 Views:97 Category:Python
-
This tutorial showed you how to replace multiple characters in a string in Python. Suppose we want to remove special characters from a string and replace them with spaces. The list of special characters to remove is !#$%^*() . Additionally,
How to remove the last character from a string in Python
Publish Date:2025/05/08 Views:141 Category:Python
-
A Python string is a combination of characters enclosed in double or single quotes. Python provides multiple functions to manipulate strings. This article will show you different ways to remove the last character and specific characters fro
How to Remove a Substring from a String in Python
Publish Date:2025/05/08 Views:182 Category:Python
-
This tutorial explains how to delete a substring in a string in Python. It will show you that strings cannot just be deleted, but only replaced. This tutorial also lists some sample codes to clarify the concepts, as the method has changed c
Get parent directory in Python
Publish Date:2025/05/08 Views:109 Category:Python
-
This tutorial will explain various ways to get the parent directory of a path in Python. A parent directory is a directory above or above a given directory or file. For example, C:\folder\subfolder\myfile.txt the parent directory of the pat
Catching keyboard interrupt errors in Python
Publish Date:2025/05/08 Views:106 Category:Python
-
The error occurs when a user manually tries to stop a running program using Ctrl + C or Ctrl + , or in the case of Jupyter Notebook by interrupting the kernel . To prevent accidental use of , which often occurs , we can use exception handli