Run Same Function in Parallel with Different Parameters - Python
Last Updated :
07 Mar, 2025
Running the same function in parallel with different parameters involves executing the function multiple times simultaneously, each time with a different set of inputs. For example, if we want to compute the square of each number in the list [0, 1, 2, 3, 4], instead of processing them one by one, running them in parallel can significantly reduce execution time by processing multiple numbers at once. The result would be [0, 1, 4, 9, 16], computed concurrently.
Using joblib.parallel
joblib.Parallel efficiently parallelizes computations, optimizing CPU and memory usage, especially in machine learning and data processing. The delayed() enables easy parallel execution with minimal inter-process communication.
Python
from joblib import Parallel, delayed
def square(val):
return val * val
if __name__ == '__main__':
inputs = [0, 1, 2, 3, 4]
res = Parallel(n_jobs=4)(delayed(square)(val) for val in inputs)
print(res)
Output
[0, 1, 4, 9, 16]
Explanation: joblib.Parallel parallelize the execution of the square function across multiple inputs. The delayed() function wraps square, enabling it to run independently for each value in inputs. With n_jobs=4, up to four processes execute in parallel, improving efficiency.
Using mutliprocessing.Pool
multiprocessing.Pool enables asynchronous function execution across multiple processes, efficiently distributing tasks. The starmap()function handles multiple parameters, making it ideal for CPU-bound tasks.
Python
import multiprocessing
def sq(i, v):
return i, v * v # Return index and square of value
if __name__ == '__main__':
n = 4 # Number of processes
inp = [0, 1, 2, 3, 4] # Input list
p = [(i, inp[i]) for i in range(len(inp))] # Create (index, value) pairs
with multiprocessing.Pool(processes=n) as pool:
r = pool.starmap(sq, p) # Parallel execution
_, r = zip(*r) # Extract squared values
print(list(r))
Explanation: This code uses multiprocessing.Pool to parallelize squaring a list of numbers. It defines sq(i, v) to return the square of v with its index, creates index-value pairs and distributes computation using starmap().
Using concurrent.futures.ProcessPoolExecutor
ProcessPoolExecutor offers a high-level interface for parallel execution, handling process creation internally. It simplifies usage over multiprocessing.Pool with slight overhead, making it ideal for moderate parallel tasks.
Python
import concurrent.futures
def sq(v):
return v * v # Return square of value
def run():
inp = [0, 1, 2, 3, 4] # Input list
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as ex:
res = list(ex.map(sq, inp)) # Parallel execution
return res
if __name__ == '__main__':
out = run()
print(out)
Explanation: ProcessPoolExecutor parallelize the sq function across multiple inputs. With max_workers=4, up to four processes run simultaneously. The map() function applies sq() to each value in inp, executing tasks in parallel.
Using mutliprocessing.Process with a loop
This method manually creates and manages multiple processes, each executing the target function independently. Unlike Pool, which manages processes automatically, this approach gives full control over process creation. However, it has higher overhead and is only recommended when each process operates independently without shared data.
Python
import multiprocessing
import time
def worker_function(id):
time.sleep(1)
print(f"I'm the process with id: {id}")
if __name__ == '__main__':
processes = []
for i in range(5):
p = multiprocessing.Process(target=worker_function, args=(i,))
p.start()
processes.append(p)
for p in processes:
p.join()
Output
I'm the process with id: 0
I'm the process with id: 1
I'm the process with id: 2
I'm the process with id: 3
I'm the process with id: 4
Explanation: Each process runs worker_function, which prints its ID after a 1-second delay. The start() method launches the processes and join() ensures all complete before exiting.
Similar Reads
Python Function Parameters and Arguments Parameters are variables defined in a function declaration. This act as placeholders for the values (arguments) that will be passed to the function. Arguments are the actual values that you pass to the function when you call it. These values replace the parameters defined in the function. Although t
3 min read
How to Pass Optional Parameters to a Function in Python In Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar
5 min read
Decorators with parameters in Python Prerequisite: Decorators in Python, Function DecoratorsWe know Decorators are a very powerful and useful tool in Python since it allow programmers to modify the behavior of functions or classes. In this article, we will learn about the Decorators with Parameters with the help of multiple examples. P
4 min read
Crontab - Running a Python script with parameters Scheduling python scripts with crontab is fundamental when it comes to automating tasks using python. We will see how to schedule python scripts and pass the necessary parameters as well. The Cron job utility is a time-based job scheduler in Unix. It allows the user to run the file at a given time a
2 min read
How to run same function on multiple threads in Python? In a large real-world application, the modules and functions have to go through a lot of input and output-based tasks like reading or updating databases, communication with different micro-services, and request-response with clients or peers. These tasks may take a significant amount of time to comp
3 min read
Run Tests in Parallel with PyTest Testing is one of the key factors of the application and code development. It is necessary whenever a team or an individual aims for a stable and performance-efficient product in a production environment. It also acts as a confidence booster for the developers as well as makes code modifications and
4 min read
Python - pass multiple arguments to map function The map() function is a built-in function in Python, which applies a given function to each item of iterable (like list, tuple etc.) and returns a list of results or map object. Syntax : map( function, iterable ) Parameters : function: The function which is going to execute for each iterableiterable
3 min read
Executing functions with multiple arguments at a terminal in Python Commandline arguments are arguments provided by the user at runtime and gets executed by the functions or methods in the program. Python provides multiple ways to deal with these types of arguments. The three most common are: Using sys.argv Using getopt module/li> Using argparse module The Python
4 min read
Periodically Execute a Function with asyncio in Tornado The primary benefit is improved performance. Asynchronous programming allows your application to efficiently handle tasks that may block the main thread, such as network operations or I/O-bound tasks. This can lead to better responsiveness and scalability. Also by controlling the frequency of period
4 min read
Pass a List to a Function in Python In Python, we can pass a list to a function, allowing to access or update the list's items. This makes the function more versatile and allows us to work with the list in many ways.Passing list by Reference When we pass a list to a function by reference, it refers to the original list. If we make any
2 min read