Track A Rolling Window With container/ring

Maintain a fixed-capacity latency window in container/ring, overwriting the oldest slot and ignoring unfilled nil nodes during summary scans.

GoResilience

Code

snippet
package main

import (
	"container/ring"
	"fmt"
)

func summarize(r *ring.Ring) (values []int, avg float64) {
	var sum int
	r.Do(func(v any) {
		if n, ok := v.(int); ok {
			values = append(values, n)
			sum += n
		}
	})
	if len(values) > 0 {
		avg = float64(sum) / float64(len(values))
	}
	return values, avg
}

func main() {
	window := ring.New(4)
	for _, ms := range []int{18, 24} {
		window.Value = ms
		window = window.Next()
	}
	vals, avg := summarize(window)
	fmt.Printf("warmup (%d/4): %v avg=%.1fms\n", len(vals), vals, avg)

	for _, ms := range []int{30, 42, 16, 28} {
		window.Value = ms
		window = window.Next()
	}
	vals, avg = summarize(window)
	fmt.Printf("steady (%d/4): %v avg=%.1fms\n", len(vals), vals, avg)
}

Code mechanics — Track A Rolling Window With container/ring

Track A Rolling Window With container/ring reduces to the functions summarize and main.

The file repeats itself only inside for _, ms := range []int{18, 24}.

Caveats

  • Fully isolated example — imports strictly standard runtime components already bundled.

Using it

Signature: func summarize(r *ring.Ring) (values []int, avg float64)

The file’s steps show up in the output as warmup (, steady (.

Execute the file and main walks through summarize, in that order.

Key statements

for _, ms := range []int{30, 42, 16, 28} {
	window.Value = ms
	window = window.Next()
}
for _, ms := range []int{18, 24} {
	window.Value = ms
	window = window.Next()
}
values = append(values, n)

Interactive Tools for This Topic

FAQ

What does Track A Rolling Window With container/ring print when run?
Running the file directly is enough — expect labeled output lines such as `warmup (`, `steady (`.