Skip to content

Commit 0ac629d

Browse files
committed
add performance evaluation
1 parent d6a1e53 commit 0ac629d

1 file changed

Lines changed: 48 additions & 9 deletions

File tree

lectures/numpy.md

Lines changed: 48 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1451,9 +1451,24 @@ Recall that [broadcasting](broadcasting) in Numpy can help us conduct element-wi
14511451
In this exercise, try to use a `for` loop to replicate the result of the following code
14521452

14531453
```{code-cell} python3
1454-
x = np.random.randn(4, 4)
1455-
y = np.random.randn(4)
1456-
x / y
1454+
import quantecon as qe
1455+
1456+
np.random.seed(123)
1457+
x = np.random.randn(1000, 100, 100)
1458+
y = np.random.randn(100)
1459+
qe.tic()
1460+
A = x / y
1461+
qe.toc()
1462+
```
1463+
1464+
Observe the time difference between the broadcasting and the `for` loop you implement.
1465+
1466+
1467+
```{code-cell} python3
1468+
---
1469+
tags: [hide-output]
1470+
---
1471+
print(A)
14571472
```
14581473

14591474
```{exercise-end}
@@ -1467,12 +1482,36 @@ x / y
14671482
Here is one solution
14681483

14691484
```{code-cell} python3
1470-
A = np.empty_like(x)
1471-
n = len(x)
1472-
for i in range(n):
1473-
for j in range(n):
1474-
A[i, j] = x[i, j] / y[j]
1475-
print(A)
1485+
1486+
np.random.seed(123)
1487+
x = np.random.randn(1000, 100, 100)
1488+
y = np.random.randn(100)
1489+
1490+
qe.tic()
1491+
B = np.empty_like(x)
1492+
d1, d2, d3 = x.shape
1493+
for i in range(d1):
1494+
for j in range(d2):
1495+
for n in range(d3):
1496+
B[i, j, n] = x[i, j, n] / y[n]
1497+
qe.toc()
1498+
```
1499+
1500+
Note that the `for` loop solution takes about 250 times longer than broadcasting operation on this machine.
1501+
1502+
Compare your answer with the broadcast operation
1503+
1504+
```{code-cell} python3
1505+
---
1506+
tags: [hide-output]
1507+
---
1508+
print(B)
1509+
```
1510+
1511+
You can also use `array_equal()` to check your answer
1512+
1513+
```{code-cell} python3
1514+
print(np.array_equal(A, B))
14761515
```
14771516

14781517
```{solution-end}

0 commit comments

Comments
 (0)