Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Implementing Benchmarking | Understanding and Measuring Performance
Optimization Techniques in Python

book
Challenge: Implementing Benchmarking

Task

Swipe to start coding

Let's practice benchmarking by comparing two approaches to squaring the elements of a NumPy array. The first approach, the slower one, uses a for loop to square each element individually, while the second approach leverages vectorization. Don't worry if this concept sounds unfamiliar—we'll discuss it later in the course.

Your task for now is the following:

  1. Define two functions:
    • The first, named square_array_slow, should take a single parameter array;
    • The second, named square_array_fast, should also take the same parameter.
  2. Decorate both functions with the timeit_decorator and set number to 100.

Solution

# Import the benchmarking decorator
import os
os.system('wget https://content-media-cdn.codefinity.com/courses/8d21890f-d960-4129-bc88-096e24211d53/section_1/chapter_3/decorators.py 2>/dev/null')
from decorators import timeit_decorator
import numpy as np
from copy import deepcopy

numbers = np.arange(100000)

# Define and decorate the first function
@timeit_decorator(number=100)
def square_array_slow(array):
array = deepcopy(array)
for i in range(len(array)):
# Square the element
array[i] = array[i] ** 2
return array

# Define and decorate the second function
@timeit_decorator(number=100)
def square_array_fast(array):
array = deepcopy(array)
# Square each element using vectorization
return array ** 2

squares_array_1 = square_array_slow(numbers)
squares_array_2 = square_array_fast(numbers)
# Check if the arrays are equal
if np.array_equal(squares_array_1, squares_array_2):
print('The arrays are equal')

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 4
# Import the benchmarking decorator
import os
os.system('wget https://content-media-cdn.codefinity.com/courses/8d21890f-d960-4129-bc88-096e24211d53/section_1/chapter_3/decorators.py 2>/dev/null')
from decorators import timeit_decorator
import numpy as np
from copy import deepcopy

numbers = np.arange(100000)

# Define and decorate the first function
___
___:
array = deepcopy(array)
for i in range(len(array)):
# Square the element
array[i] = array[i] **2
return array

# Define and decorate the second function
___
___:
array = deepcopy(array)
# Square each element using vectorization
return array ** 2

squares_array_1 = square_array_slow(numbers)
squares_array_2 = square_array_fast(numbers)
# Check if the arrays are equal
if np.array_equal(squares_array_1, squares_array_2):
print('The arrays are equal')

Ask AI

expand
ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt