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:
- Define two functions:
- The first, named
square_array_slow
, should take a single parameterarray
; - The second, named
square_array_fast
, should also take the same parameter.
- The first, named
- Decorate both functions with the
timeit_decorator
and setnumber
to100
.
Solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 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?
Thanks for your feedback!
Section 1. Chapter 4
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 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
Ask anything or try one of the suggested questions to begin our chat