持续时间单位

禅:

我在代码中

    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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章