In [1]:
import numpy as np
data = np.random.normal(size=(100, 100))
In [2]:
%timeit -r 10 -n 100000 np.sqrt(np.mean(np.square(data)))
%timeit -r 10 -n 100000 np.linalg.norm(data.flat, ord=2) / np.sqrt(data.size)
%timeit -r 10 -n 100000 np.linalg.norm(data.ravel(), ord=2) / np.sqrt(data.size)
20 µs ± 59.3 ns per loop (mean ± std. dev. of 10 runs, 100000 loops each)
16.1 µs ± 252 ns per loop (mean ± std. dev. of 10 runs, 100000 loops each)
13 µs ± 1.33 µs per loop (mean ± std. dev. of 10 runs, 100000 loops each)
In [3]:
assert np.allclose(np.sqrt(np.mean(np.square(data))), np.linalg.norm(data.ravel(), ord=2) / np.sqrt(data.size))
print("thumbs up!")
thumbs up!
In [4]:
%timeit -r 10 -n 100000 np.sqrt(np.mean(np.square(data), axis=0))
%timeit -r 10 -n 100000 np.linalg.norm(data, ord=2, axis=0) / np.sqrt(data.shape[0])
20.8 µs ± 69.1 ns per loop (mean ± std. dev. of 10 runs, 100000 loops each)
21.3 µs ± 92 ns per loop (mean ± std. dev. of 10 runs, 100000 loops each)
In [5]:
assert np.allclose(np.sqrt(np.mean(np.square(data), axis=0)), np.linalg.norm(data, ord=2, axis=0) / np.sqrt(data.shape[0]))
print("thumbs up!")
thumbs up!