Speed Up Data Pre‑processing with Python’s Multiprocessing
3 min read
- python
- automation
- data‑science
- multiprocessing
When you start a machine‑learning project, the model often looks ready in minutes, but the data‑pre‑processing can take hours.
The question is simple: Can we make that step faster without rewriting everything in a new language?
The answer is yes. Python’s built‑in multiprocessing library lets you run independent tasks on multiple CPU cores. Below is a step‑by‑step guide that works for any tabular or image‑based pipeline.
Why Multiprocessing Works for Pre‑processing
- Pre‑processing steps (e.g., cleaning, feature extraction, resizing) are usually CPU‑bound.
- Each row or file can be handled independently – no need for shared state.
- Running them on separate cores reduces total wall‑clock time roughly by the number of cores you use.
Setting Up a Simple Pipeline
Assume you have a folder of images and you need to:
- Load the image.
- Resize it to 224 × 224.
- Convert it to a NumPy array.
- Save the array as a
.npyfile.
Here’s the serial version (single core) for reference:
import os, numpy as np
from PIL import Image
def process_image(path, out_dir):
img = Image.open(path).convert('RGB')
img = img.resize((224, 224))
arr = np.array(img)
base = os.path.splitext(os.path.basename(path))[0]
np.save(os.path.join(out_dir, f'{base}.npy'), arr)
for f in os.listdir('images'):
process_image(os.path.join('images', f), 'processed')
Running this on a few thousand images can take many minutes.
Parallelising with multiprocessing
1. Choose a worker function
The function must be picklable (top‑level, not nested). Our process_image already satisfies that.
2. Create a pool of workers
from multiprocessing import Pool, cpu_count
def main():
img_dir = 'images'
out_dir = 'processed'
os.makedirs(out_dir, exist_ok=True)
# List full paths
paths = [os.path.join(img_dir, f) for f in os.listdir(img_dir)]
# Use all available cores, but you can limit it: processes=4
with Pool(processes=cpu_count()) as pool:
# starmap passes each argument tuple to the function
pool.starmap(process_image, [(p, out_dir) for p in paths])
if __name__ == '__main__':
main()
Poolcreates separate Python processes, each with its own interpreter and memory space.starmapdistributes the list of argument tuples across the workers.
3. Handle exceptions gracefully
If a single file is corrupted, you don’t want the whole pool to crash.
def safe_process(path, out_dir):
try:
process_image(path, out_dir)
except Exception as e:
print(f'Failed {path}: {e}')
Replace process_image with safe_process in the starmap call.
Tips for Real‑World Projects
- Chunk large lists: For very big datasets, feed the pool in smaller batches to avoid overwhelming the OS with open file handles.
- Avoid heavy global state: Keep data inside the worker function; sharing large objects via
multiprocessing.Managercan negate speed gains. - Profile first: Use
timeitorcProfileon the serial version to confirm the bottleneck is CPU‑bound. - Consider I/O limits: If your preprocessing reads from a network drive, you may hit bandwidth limits before CPU becomes the bottleneck.
When Not to Use Multiprocessing
- Tasks are I/O‑bound (e.g., waiting for a web API). Use
asyncioor threading instead. - The function relies on libraries that are not fork‑safe (some older C extensions). Test a small subset first.
Quick Benchmark
import time
start = time.time()
# run serial version
...
print('Serial time:', time.time() - start)
start = time.time()
# run parallel version
...
print('Parallel time:', time.time() - start)
On a typical laptop with 8 cores, the parallel run was about 5‑6× faster for 10 000 images.
Key takeaways
- Multiprocessing lets you use all CPU cores for independent preprocessing steps.
- Keep the worker function simple and picklable; wrap it in a try/except to avoid crashes.
- Profile first and watch for I/O bottlenecks; parallelism helps when the work is CPU‑bound.