Learning about Python Multiprocessing Technique

CK CK 3788 
Created at  
591 0 0

Multiprocessing is useful for a variety of reasons, particularly when dealing with computationally intensive tasks that can benefit from parallel execution. Here are some key advantages of using multiprocessing:

Here’s an example of using Python’s multiprocessing module to sum the values in an array containing integers from 0 to 1,000,000. This script will split the array into chunks, process each chunk in parallel to calculate partial sums, and then combine these partial sums to get the final result.

Python Script

import multiprocessing

# Function to calculate the sum of a chunk of the array
def sum_chunk(chunk):
    return sum(chunk)

# Function to split the array into chunks
def chunkify(lst, n):
    return [lst[i::n] for i in range(n)]

# Function to sum the array using multiprocessing
def parallel_sum(array, num_processes):
    # Split the array into chunks
    chunks = chunkify(array, num_processes)

    # Create a pool of worker processes
    with multiprocessing.Pool(processes=num_processes) as pool:
        # Map the sum_chunk function to each chunk
        partial_sums = pool.map(sum_chunk, chunks)

    # Combine the partial sums to get the final result
    total_sum = sum(partial_sums)
    return total_sum

if __name__ == "__main__":
    # Create an array of integers from 0 to 1,000,000
    array = list(range(1_000_001))

    # Number of processes to use
    num_processes = multiprocessing.cpu_count()

    # Calculate the sum of the array using multiprocessing
    total_sum = parallel_sum(array, num_processes)
    
    print(f"Total sum of the array: {total_sum}")

Explanation:

  1. Sum Function:
    • sum_chunk(chunk): This function takes a chunk of the array and returns the sum of the elements in that chunk.
  2. Chunkify Function:
    • chunkify(lst, n): This function splits the input list lst into n roughly equal chunks.
  3. Parallel Sum Function:
    • parallel_sum(array, num_processes): This function splits the array into chunks, uses a pool of worker processes to calculate the sum of each chunk in parallel, and then combines the partial sums to get the final total sum.
  4. Main Block:
    • The array is created with integers from 0 to 1,000,000.
    • The number of processes is set to the number of CPU cores available.
    • The parallel_sum function is called to calculate the sum of the array using multiprocessing.

 

Running the Script

Save the code in a file, for example, parallel_sum.py, and run it using Python:

python parallel_sum.py

This script will utilize multiple CPU cores to efficiently sum the large array of integers. The result will be printed to the console.

Tags Multiprocessing Multiprocessing.Pool Python Python Multiprocessing multiprocessing.cpu_count() Facebook X
Comments 0
Similar posts
  1. Simple Example to get the total number of records in BigQuery with Python
    665
  2. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,067
  3. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    735
  4. Dynamic DNS Made Easy: Building a Python-Based Solution
    793
  5. Python script to list files on your Google Drive and download one of them
    939
  6. Method to maximize full CPU performance with Python
    314
  7. Uploading a file to a Google Drive Folder programmatically with Python
    3,305
  8. How to run Python 3.9 on Mac?
    647
  9. Is PyTorch Dead? Deep Learning's Enduring Role Beyond LLMs & Essential Skills
    691
  10. Forecasting with Linear Regression and KNN Regression in Python
    920
  11. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,154
  12. Harnessing the Power of Random Forest Algorithm in Python
    657
  13. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    630
  14. Python Implementation of Linear Regression
    836
  1. Video Scence Detection with PySceneDetect
    2,318
  2. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,433
  3. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    902
  4. Deleting a specific user voice from the original audio track with Python
    547
  5. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    436
  6. Creating mp3 audio file based on the text input with Python
    463
  7. Implementing Text To Speech / Audio with Python3 and pyttsx3
    354
  8. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  9. Python Simplified Assignment Operators
    533
  10. Trackback module used for Python Threading debugging
    840
  11. Python Flask with simple HTML files to server web pages along with API
    926
  12. Python Flask web server tutorial from the scratch
    618
  13. Simple Web Server based in Python
    368
  14. Thread Implementation in Python
    507
  15. A shell script that activates a Python virtual environment and then runs a specific Python script
    741
  16. Simple Example to get the total number of records in BigQuery with Python
    665
  17. Using BigQuery in Python
    407
  18. Python Web Programming based on Django from the Scratch
    366
  19. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    184
  20. How do I determine the client IP type in Python - IPv4 or IPv6
    760
  21. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,230
  22. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  23. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,067
  24. Dynamic DNS Made Easy: Building a Python-Based Solution
    793
  25. Milvus & FAISS: Decoding Their ML Synergy
    276
  26. Save clustering result (aka dictionary) in JSON and Reuse loaded result
    376
  27. Forecasting with Linear Regression and KNN Regression in Python
    920
  28. Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction
    1,430
  29. Uvicorn, Gunicorn: Proving Your Production Prowess
    395
  30. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,154
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,708
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    197
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    232
  17. The Concept of Scaffolding in AI Agents
    221
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    575
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    252
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    326
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252