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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.