Parallel computing in Python (in 60 seconds or less)

Hey there,

If your Python programs are slower than you'd like you can often speed them up by *parallelizing* them.

Basically, parallel computing allows you to carry out many calculations at the same time, thus reducing the amount of time it takes to run your program to completion.

I know, this sounds fairly vague and complicated somehow...but bear with me for the next 50 seconds or so.

Here's an end-to-end example of parallel computing in Python 2/3, using only tools built into the Python standard library—

Ready? Go!

First, we need to do some setup work. We'll import the "collections" and the "multiprocessing" module so we can use Python's parallel computing facilities and define the data structure we'll work with:

import collections
import multiprocessing

Second, we'll use "collections.namedtuple" to define a new (immutable) data type we can use to represent our data set, a collection of scientists:

Scientist = collections.namedtuple('Scientist', [
    'name',
    'born',
])

scientists = (
    Scientist(name='Ada Lovelace', born=1815),
    Scientist(name='Emmy Noether', born=1882),
    Scientist(name='Marie Curie', born=1867),
    Scientist(name='Tu Youyou', born=1930),
    Scientist(name='Ada Yonath', born=1939),
    Scientist(name='Vera Rubin', born=1928),
    Scientist(name='Sally Ride', born=1951),
)

Third, we'll write a "data processing function" that accepts a scientist object and returns a dictionary containing the scientist's name and their calculated age: 

def process_item(item):
    return {
        'name': item.name,
        'age': 2017 - item.born
    }

The process_item() function just represents a simple data transformation to keep this example short and sweet—but you could swap it out with a much more complex computation no problem. 

(20 seconds remaining)

Fourth, and this is where the real parallelization magic happens, we'll set up a "multiprocessing pool" that allows us to spread our calculations across all available CPU cores. 

Then we call the pool's map() method to apply our process_item() function to all scientist objects, in parallel batches:

pool = multiprocessing.Pool()
result = pool.map(process_item, scientists)

Note how batching and distributing the work across multiple CPU cores, performing the work, and collecting the results are all handled by the multiprocessing pool. How great is that?

Fifth, we're all done here with 5 seconds remaining—

Let's print the results of our data transformation to the console so we can make sure the program did what it was supposed to:

print(tuple(result))

That's the end of our little program. And here's what you should expect to see printed out on your console:

({'name': 'Ada Lovelace', 'age': 202},
 {'name': 'Emmy Noether', 'age': 135},
 {'name': 'Marie Curie', 'age': 150},
 {'name': 'Tu Youyou', 'age': 87},
 {'name': 'Ada Yonath', 'age': 78},
 {'name': 'Vera Rubin', 'age': 89},
 {'name': 'Sally Ride', 'age': 66})

Isn't Python just lovely?

Now, obviously I took some shortcuts here and picked an example that made parallelization seem effortless—

But, I stand by the lessons learned here:

- If you know how to structure and represent your data, parallelization is convenient and feels completely natural. As a Pythonista, you should pick up the basics of functional programming for this reason.

- Python is a joy to work with and eminently suitable for these kinds of programming tasks.

— Dan Bader

Older messages

Python side projects & getting a job

Sunday, December 20, 2020

Hey there, Where do you find inspiration for Python side projects? It's a question I often hear from Pythonistas looking to build up a portfolio they can show to potential employers. So here's

[Sublime + Python Setup] Sublime Text is just a blank canvas…

Saturday, December 19, 2020

Hey there, When I became serious about optimizing Sublime Text with plugins, it was hard for me to separate the wheat from the chaff. Without a real guideline or roadmap I resorted to installing *any*

[PythonistaCafe] Q&A

Saturday, December 19, 2020

Hey there, At this point you should have a pretty good idea of what PythonistaCafe is about and what makes it special. In this email I want to answer some common questions that I get asked about the

[Sublime + Python Setup] Grumpy old greybeard with a whitespace problem

Friday, December 18, 2020

One fateful day, the Agile Gods that be decided to “add some firepower” to my little team… And so, developer Paul joined (name changed to protect the guilty). Before I dive into this story, let me ask

[PythonistaCafe] What's in PythonistaCafe for you?

Friday, December 18, 2020

Hey there, A couple of years ago I'd become quite interested in martial arts. Hours upon hours of watching "The Karate Kid" growing up must've taken their toll on me... And so, I

You Might Also Like

Kotlin Weekly #407

Sunday, May 19, 2024

ISSUE #407 19th of May 2024 Hello Kotliners! The Google I/O just finished this week with a huge announcement for us, with Google supporting now Kotlin Multiplatform on Android, and the KotlinConf will

Learn How to Use AI to Reach Your Full Potential, newsletterest1!

Sunday, May 19, 2024

3 Ways AI Can Help Your Writing ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌ ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌ ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌ ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌  ͏ ‌

Software Testing Weekly - Issue 220

Saturday, May 18, 2024

Software Testing Conferences 📚 View on the Web Archives ISSUE 220 May 18th 2024 COMMENT Welcome to the 220th issue! Have you ever been to a testing conference? They're a great way to learn about

📶 Is a Cellular iPad Worth It? — How to Prevent YouTube From Taking Over Your Screensaver

Saturday, May 18, 2024

Also: This Robot Vacuum Can Clean Stairs, and More! How-To Geek Logo May 18, 2024 📩 Get expert reviews, the hottest deals, how-to's, breaking news, and more delivered directly to your inbox by

Weekend Reading — Objection-oriented programming

Saturday, May 18, 2024

This week we find a power-up box, replace GitHub Actions with Maven XMLs, avoid the worst website in the world, revisit RTO policies, “listen” to OpenAI employees, watch our Slack private messages, do

Daily Coding Problem: Problem #1445 [Easy]

Saturday, May 18, 2024

Daily Coding Problem Good morning! Here's your coding interview problem for today. This problem was asked by Jane Street. The United States uses the imperial system of weights and measures, which

You don’t have to take our word for it…

Saturday, May 18, 2024

You can probably tell how excited we are to re-launch our Gigantic courses – which bring on-demand product management training for today's modern Product Managers and Product Leaders. In fact, we

🐍 New Python tutorials on Real Python

Saturday, May 18, 2024

Hey there, There's always something going on over at realpython.com as far as Python tutorials go. Here's what you may have missed this past week: What Is the __pycache__ Folder in Python? In

Visualized | Life Expectancy by Region (1950-2050F) 📊

Saturday, May 18, 2024

This map shows life expectancy at birth for key global regions, from 1950 to 2050F. View Online | Subscribe Presented by Voronoi: The App Where Data Tells the Story FEATURED STORY Life Expectancy by

New Wi-Fi Vulnerability Enables Network Eavesdropping via Downgrade Attacks

Saturday, May 18, 2024

THN Daily Updates Newsletter cover The DevSecOps Playbook: Deliver Continuous Security at Speed ($19.00 Value) FREE for a Limited Time A must-read guide to a new and rapidly growing field in