Monotonic Elapsed Timing With time.Since

Measure elapsed time with time.Since so wall-clock adjustments never skew durations, and strip the monotonic reading with Round(0) before persisting.

GoData Integrity

Code

gosnippet
31 lines
package main

import (
	"fmt"
	"time"
)

func summarize(readings []int) int {
	total := 0
	for _, r := range readings {
		total += r * r
	}
	return total
}

func main() {
	start := time.Now()

	total := summarize(make([]int, 200_000))
	elapsed := time.Since(start)

	fmt.Println("squares:", total)
	fmt.Println("elapsed microseconds:", elapsed.Microseconds())

	// Round(0) 剥离单调钟读数:只剩墙钟,用于序列化与落库
	wallOnly := start.Round(0)
	fmt.Println("same instant:", start.Equal(wallOnly))

	// time.Since 对两种时间都能用:两边都带单调读数时才走单调钟
	fmt.Println("since wall-only positive:", time.Since(wallOnly) > 0)
}

How it works

Count the functions summarize and main as the entire surface area of Monotonic Elapsed Timing With time.Since.

The one repetition in this snippet is the loop for _, r := range readings.

Applying it

Entry signature: func summarize(readings []int) int

Running the file prints labeled results such as squares:, elapsed microseconds:, same instant: — each operation’s effect is visible in the output.

Running the file executes main, which drives summarize in order.

Statements that matter

func summarize(readings []int) int {
total := 0
for _, r := range readings {
total += r * r
}
return total
}
total := summarize(make([]int, 200_000))

Interactive Tools for This Topic

FAQ

What does Monotonic Elapsed Timing With time.Since print when run?
Running the file directly is enough — expect labeled output lines such as `squares:`, `elapsed microseconds:`, `same instant:`.