I am trying to write a fast method to calculate the cumulative sum over a one-dimensional array of type double, however my naive implementation is very slow and I'm not sure how I can speed up my method.
My first approach was to create an empty array of same dimensions and populate it with the respective cumulative sums in a for loop.
void cumsum_d(int size, double arr[size]) {
double* out = (double*)malloc(size*sizeof(double));
for (int i = 0; i < size; ++i) {
double temp = 0;
for (int j = 0; j < i+1; ++j) {
temp += arr[j];
}
out[i] = temp;
}
for (int i = 0; i < size; ++i) {
arr[i] = out[i];
}
free(out);}
My second attempt was to modify the array in place using recursion
void cumsum_d2(int size, double arr[size], int ind) {
if (ind == 0) {
return;
}
double temp = 0;
for (int i = 0; i < ind+1; ++i) {
temp += arr[i];
}
arr[ind] = temp;
cumsum_d2(size, arr, ind-1);}
For an array of length 1000 this has a runtime of approx. 1ms whereas e.g. the NumPy implementation NumPy.cumsum() only takes around 60μs.
Are there any tips/tricks for how I can speed up my code, or are there any major flaws?