Recipe 33 | Calculating Cumulative Sum |
Task
Josh, the ops team lead, asks you to help them with monitoring the server you are developing. He says:
We have a cumSum function that calculates the cumulative sum of a slice of metrics. For example, the cumulative sum of []int{1, 2, 3} is []int{1, 3, 6}. When we use the function, we see that it gets slow on large slices, and the garbage collector starts to work a lot. Can you please have a look and fix it?
You look at the current code to calculate the cumulative sum:
| // cumSum returns the cumulative sum of values |
| // cumSum([]int{1, 2, 3}) → []int{1, 3, 6} |
| func cumSum(values []int) []int { |
| var cs []int |
| s := 0 |
| for _, val := range values { |
| s += val ... |
Get Effective Go Recipes now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.