Mean Calculation in Python with NumPy and Concurrency

In this section, we explore the calculation of means in a large matrix using Python's NumPy library, and how to enhance performance using concurrency with asyncio and threading.

Mean Calculation with NumPy

NumPy is a powerful library for numerical computations in Python. It provides a convenient function, mean, which can compute the mean of elements along a specified axis of an array. This is particularly useful for large datasets where performance is a concern.

Example: Calculating Means of a Large Matrix

Consider a scenario where we have a large matrix with 4,000,000,000 data points distributed across 50 rows. Our task is to compute the mean for each row efficiently.

Listing 7.18 Means of a large matrix with NumPy

import numpy as np
import time

data_points = 4000000000
rows = 50
columns = int(data_points / rows)

matrix = np.arange(data_points).reshape(rows, columns)

s = time.time()

res = np.mean(matrix, axis=1)

e = time.time()
print(e - s)

In this script, we first create an array with 4,000,000,000 integer data points. The array is reshaped into a matrix with 50 rows. Using NumPy's mean function with an axis of 1, we calculate the mean for each row. This operation is efficient and typically completes in about 25–30 seconds on an 8-core 2.4 GHz CPU.

Enhancing Performance with Concurrency

To further optimize the performance, especially when dealing with very large datasets, we can leverage concurrency. By using Python's asyncio library along with threading, we can perform mean calculations in parallel.

Example: Threading with NumPy

To calculate the mean for each row in a separate thread, we define a function mean_for_row and use a thread pool executor to manage the threads.

Listing 7.19 Threading with NumPy

import functools
from concurrent.futures.thread import ThreadPoolExecutor
import numpy as np
import asyncio
from util import async_timed

def mean_for_row(arr, row):
    return np.mean(arr[row])

data_points = 4000000000
rows = 50
columns = int(data_points / rows)

matrix = np.arange(data_points).reshape(rows, columns)

@async_timed()
async def main():
    loop = asyncio.get_running_loop()
    with ThreadPoolExecutor() as pool:
        tasks = []
        for i in range(rows):
            mean = functools.partial(mean_for_row, matrix, i)
            tasks.append(loop.run_in_executor(pool, mean))

        results = asyncio.gather(*tasks)

asyncio.run(main())

In this example, we define a mean_for_row function to calculate the mean for a single row. The main coroutine uses a thread pool executor to run each row's mean calculation in a separate thread. The asyncio.gather function is used to wait for all the calculations to complete. This approach can significantly reduce the computation time by utilizing multiple CPU cores effectively.