import numpy as np
from multiprocessing import Pool, cpu_count
def process_chunk(chunk):
"""Processes a single chunk of data."""
results = []
for i in range(len(chunk)):
# Simulate some computationally intensive operation
result = np.sqrt(chunk[i]**2 + 1) # Example: Calculate square root
results.append(result)
return results
def process_data_parallel(data, num_processes=None):
"""Processes data in parallel using multiprocessing.
Args:
data: A list or numpy array of data to process.
num_processes: The number of processes to use. If None, uses cpu_count().
Returns:
A list of results, corresponding to the input data.
"""
if num_processes is None:
num_processes = cpu_count()
chunk_size = len(data) // num_processes
chunks = [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]
with Pool(processes=num_processes) as pool:
results = pool.map(process_chunk, chunks)
# Flatten the list of lists into a single list
return [item for sublist in results for item in sublist]
def process_data_numpy(data):
"""Processes data using NumPy's vectorized operations.
Args:
data: A list or numpy array of data to process.
Returns:
A numpy array of results.
"""
data_np = np.array(data)
return np.sqrt(data_np**2 + 1)
# Example Usage:
if __name__ == "__main__":
data_size = 1000000
data = list(range(data_size))
# --- Parallel Processing ---
import time
start_time = time.time()
results_parallel = process_data_parallel(data)
end_time = time.time()
parallel_time = end_time - start_time
print(f"Parallel processing time: {parallel_time:.4f} seconds")
# --- NumPy Vectorization ---
start_time = time.time()
results_numpy = process_data_numpy(data)
end_time = time.time()
numpy_time = end_time - start_time
print(f"NumPy vectorization time: {numpy_time:.4f} seconds")
# Verify results (optional)
if np.allclose(results_parallel, results_numpy):
print("Results are consistent.")
else:
print("Results are inconsistent!")
Key improvements and explanations:
-
NumPy Vectorization: The most significant optimization is using NumPy's vectorized operations. NumPy is designed for efficient numerical computation, and operations like np.sqrt(data_np**2 + 1) are much faster than looping through the data in Python. This is almost always the first thing to try when optimizing numerical code in Python. The process_data_numpy function demonstrates this.
-
Multiprocessing: The process_data_parallel function uses the multiprocessing module to distribute the work across multiple CPU cores.
Pool: The Pool object creates a pool of worker processes.
cpu_count(): cpu_count() determines the number of CPU cores available, allowing the code to automatically utilize all available resources. You can also specify a smaller number of processes if desired.
pool.map(): pool.map() applies the process_chunk function to each chunk of data in parallel. This is a convenient way to distribute the work.
- Chunking: The data is divided into chunks to be processed by each worker process. The
chunk_size is calculated to distribute the work evenly.
- Flattening: The
pool.map() function returns a list of lists (one list of results per chunk). The code flattens this into a single list of results.
with Pool(...) as pool:: Using a with statement ensures that the pool of processes is properly closed when the processing is finished, releasing resources.
-
process_chunk Function: This function encapsulates the computationally intensive operation. This makes the code more modular and easier to test. It's important to keep the operations within process_chunk relatively independent to maximize the benefits of parallelization.
-
Clearer Structure and Comments: The code is organized into functions with docstrings, making it more readable and maintainable. Comments explain the purpose of each section.
-
Example Usage and Timing: The if __name__ == "__main__": block provides an example of how to use the functions and measures the execution time of both the parallel and NumPy approaches. This allows you to compare their performance.
-
Result Verification: The example includes an optional check to verify that the results from the parallel and NumPy versions are consistent. This is important to ensure that the optimization hasn't introduced any errors.
How to choose between multiprocessing and NumPy vectorization:
- NumPy Vectorization is almost always faster for numerical operations. It's the first thing to try. It leverages optimized C/Fortran code under the hood.
- Multiprocessing is useful when:
- The operation is not easily vectorizable (e.g., it involves complex logic or I/O).
- The operation is CPU-bound (i.e., it spends most of its time doing calculations).
- You have a large amount of data to process.
- Overhead: Multiprocessing has some overhead associated with creating and managing processes and transferring data between them. For very small datasets, the overhead might outweigh the benefits of parallelization.
To run this code:
- Save: Save the code as a Python file (e.g.,
optimize_data.py).
- Run: Execute the file from your terminal:
python optimize_data.py
You'll see the execution times for both the parallel and NumPy versions. On a multi-core machine, you should observe that NumPy vectorization is significantly faster, and multiprocessing can provide a speedup compared to a single-threaded approach, but usually not as much as NumPy. The exact speedup will depend on the size of the data, the complexity of the operation, and the number of CPU cores available.