If my understanding is correct, both np.sum and np.cumsum will take O(n) time. However, when I do both operations to the same matrix sequentially (on different axis), it seems the sequence of np.sum and np.cumsum makes the overall performance quite different, though the result is the same as expected.
If I do the np.cumsum along column direction (axis=1) for each row first, and then do np.sum for all the rows (axis=0), it will take longer time.
If I do the np.sum along rows (axis=0) first, then do np.cumsum for the one dimension array, it will take shorter time.
My hypothesis is that the np.cumsum will take more time on the data allocation/manipulation since it will yield more data than np.sum, so it will take longer time if there are more operations of np.cumsum.
Here is my testing code and result
import numpy as np
import time
b = np.zeros((1000, 1000))
for i in range(1000):
b[i] = np.array(range(1000))
time_start = time.time()
for i in range(1000):
c = np.cumsum(b, axis=1)
d = np.sum(c, axis=0)
time_end = time.time()
print(f"np.sum(np.cumsum(...)) time: {time_end - time_start}")
time_start = time.time()
for i in range(1000):
c = np.cumsum(np.sum(b, axis=0))
time_end = time.time()
print(f"np.cumsum(np.sum(...)) time: {time_end - time_start}")
The result is
np.sum(np.cumsum(...)) time: 3.6612446308135986
np.cumsum(np.sum(...)) time: 0.38796162605285645