← 中文资源

简体中文版本

time.Since 单调钟计时

用 time.Since 计时不惧墙钟校准:单调读数只在两边都带时参与运算;Round(0) 可剥离单调读数,落库序列化前先归一化为墙钟。

阅读英文原文

实现说明

除了函数 summarize、main,文件里再无其他定义。 重复被限制在 for _, r := range readings 里——其余代码按顺序各跑一遍。

使用要点

  • 演示输出是带标签的(squares:、elapsed microseconds:、same instant:),每个操作都会留下自己的一行标注。
  • main 的演示流程是 summarize——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「time.Since 单调钟计时」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 squares:、elapsed microseconds:、same instant: 标签标明各步骤。

入口签名:func summarize(readings []int) int

核心语句

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

代码示例

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)
}