w3resource

Comparing performance of custom ufunc and Python loop in NumPy


NumPy: Universal Functions Exercise-15 with Solution


Comparing ufunc Performance:

Write a NumPy program that compares the performance of a custom ufunc to a standard Python loop for element-wise addition on large arrays.

Sample Solution:

Python Code:

import numpy as np
import time

# Define the custom ufunc for element-wise addition
def custom_add(x, y):
    return x + y

# Convert the Python function to a NumPy ufunc
custom_ufunc_add = np.frompyfunc(custom_add, 2, 1)

# Create two large NumPy arrays
size = 1000000
array_x = np.random.rand(size)
array_y = np.random.rand(size)

# Performance comparison using standard Python loop
start_time = time.time()
result_loop = np.empty(size)
for i in range(size):
    result_loop[i] = array_x[i] + array_y[i]
time_loop = time.time() - start_time

# Performance comparison using custom ufunc
start_time = time.time()
result_ufunc = custom_ufunc_add(array_x, array_y)
result_ufunc = result_ufunc.astype(np.float64)  # Convert to numeric type if needed
time_ufunc = time.time() - start_time

# Print the results
print(f"Time taken using standard Python loop: {time_loop:.6f} seconds")
print(f"Time taken using custom ufunc: {time_ufunc:.6f} seconds")

# Verify the results are the same
assert np.allclose(result_loop, result_ufunc), "Results do not match!"
print("Both methods produce the same results.")

Output:

Time taken using standard Python loop: 0.359292 seconds
Time taken using custom ufunc: 0.140621 seconds
Both methods produce the same results.

Explanation:

  • Import Libraries:
    • Import the NumPy library for array handling and the time library for performance measurement.
  • Define Custom Function:
    • Create a custom Python function custom_add for element-wise addition.
  • Convert to ufunc:
    • Use np.frompyfunc() to convert the Python function to a NumPy ufunc for element-wise addition.
  • Create Large Arrays:
    • Generate two large random "NumPy" arrays 'array_x' and 'array_y' of specified size.
  • Python Loop Performance:
    • Measure the time taken to perform element-wise addition using a standard Python loop.
  • Custom ufunc Performance:
    • Measure the time taken to perform element-wise addition using the custom "ufunc".
  • Print Performance Results:
    • Output the time taken by both methods.
  • Verify Results: Ensure that both methods produce the same results using np.allclose(), and print a confirmation message.

Python-Numpy Code Editor: