我在代码中
fmt.Println("... ", time.Since(s1))
fmt.Println(".... ", time.Since(s2))
第一个的结果始终为µs,第二个的结果始终为ns(例如7.081µs,分别为365ns)。
是什么原因造成的?我该如何控制?我希望显示7081ns,始终为ns /
我看了看功能;我该怎么解释?
// Since returns the time elapsed since t.
// It is shorthand for time.Now().Sub(t).
func Since(t Time) Duration {
var now Time
if t.wall&hasMonotonic != 0 {
// Common case optimization: if t has monotonic time, then Sub will use only it.
now = Time{hasMonotonic, runtimeNano() - startNano, nil}
} else {
now = Now()
}
return now.Sub(t)
}
该fmt
包调用time.Duration.String()
方法(因为time.Duration
实现fmt.Stringer
接口),这将使用更小的单位(毫,微或毫微秒)如果该持续时间小于一秒。您不能直接控制它。
但是,您可以duration.Nanoseconds()
使用Itoa 将返回的纳秒数转换为字符串,例如:
formatted := strconv.Itoa(int(time.Since(s2).Nanoseconds())) + "ns"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句