Example code:
import numpy as np
import math
import time
x=np.ones((2000,2000))
start = time.time()
print(np.linalg.norm(x, 2))
end = time.time()
print("time 1: " + str(end - start))
start = time.time()
print(math.sqrt(np.sum(x*x)))
end = time.time()
print("time 2: " + str(end - start))
The output (on my machine) is:
1999.999999999991
time 1: 3.216777801513672
2000.0
time 2: 0.015042781829833984
It shows that np.linalg.norm() takes more than 3s to solve it, while the direct solution takes just 0.01s. Why is np.linalg.norm() so slow?