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

Post from Syncfusion Blogs on 11/28/2024

Thursday, November 28, 2024

New blogs from Syncfusion All Things Open 2024 Takeaways, Part 3: Freedom vs. Sustainability By Marissa Keller Outten The role of sustainability and freedom in open source was discussed at the All

Top Tech 🏆 HTC VIVE Focus Vision Review — These Clip-on Earbuds Are Simple and Sound Good

Thursday, November 28, 2024

Also: Plugable Portable Monitor Review, and More! How-To Geek Logo November 28, 2024 😎 Question Reality If you're wondering what to buy on Black Friday or during the holiday rush, this week we

Hackers Exploit Popular Game Engine to Distribute Cross-Platform Malware

Thursday, November 28, 2024

THN Daily Updates Newsletter cover Programming with GitHub Copilot: Write Better Code--Faster! ($48.00 Value) FREE for a Limited Time Accelerate your programming with the most popular AI coding tool on

Edge 452: The AI Magic Behind Google's NotebookLM Audio Features

Thursday, November 28, 2024

How does NotebookLM generate such cool podcasts? ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏

Check Out These Awesome Gifts!

Thursday, November 28, 2024

Let us help you check one thing off your to-do list with this guide to the best gifts for the holiday season. Make the holidays a little brighter with these great gift options. From health and wellness

🚀 Accelerate Your Growth As a Software Architect

Thursday, November 28, 2024

What students are saying about my courses More than 4300+ students already completed my courses. And they gave them a 4.9/5 ⭐ rating. I'd love to see your success story next on this wall of

🫵 Android Developer Previews Are Not For You — Virtual Reality Might Finally Be Socially Acceptable

Wednesday, November 27, 2024

Also: iPhone Camera vs. Digital SLR, and More! How-To Geek Logo November 27, 2024 Did You Know The band Radiohead was originally called "On a Friday"—the band was formed by high school

JSK Daily for Nov 27, 2024

Wednesday, November 27, 2024

JSK Daily for Nov 27, 2024 View this email in your browser A community curated daily e-mail of JavaScript news JavaScript Certification Black Friday Offer – Up to 54% Off! Certificates.dev, the trusted

Ranked | The World's Biggest Importers of Goods 🌎

Wednesday, November 27, 2024

As Trump tariffs are anticipated to disrupt global trade and push up prices for consumers, we show the world's biggest importers of goods. View Online | Subscribe | Download Our App >> 📱Book

Daily Coding Problem: Problem #1621 [Easy]

Wednesday, November 27, 2024

Daily Coding Problem Good morning! Here's your coding interview problem for today. This problem was asked by Google. A regular number in mathematics is defined as one which evenly divides some