号码至time.Duration
time.Duration https://golang.org/pkg/time/#Duration是一个具有int64
as its 底层类型 https://golang.org/ref/spec#Types,它存储以纳秒为单位的持续时间。
如果您知道该值,但您想要纳秒以外的值,只需乘以您想要的单位,例如:
d := 100 * time.Microsecond
fmt.Println(d) // Output: 100µs
上述之所以有效,是因为100
是一个无类型的constant https://golang.org/ref/spec#Constants,并且可以自动转换为time.Duration
其中有int64
基础类型。
请注意,如果您将该值作为键入值,则必须使用显式类型转换 https://golang.org/ref/spec#Conversions:
value := 100 // value is of type int
d2 := time.Duration(value) * time.Millisecond
fmt.Println(d2) // Output: 100ms
time.Duration
编号
So time.Duration
始终是纳秒。例如,如果您需要以毫秒为单位,您所需要做的就是除以time.Duration
以毫秒为单位的纳秒数的值:
ms := int64(d2 / time.Millisecond)
fmt.Println("ms:", ms) // Output: ms: 100
其他例子:
fmt.Println("ns:", int64(d2/time.Nanosecond)) // ns: 100000000
fmt.Println("µs:", int64(d2/time.Microsecond)) // µs: 100000
fmt.Println("ms:", int64(d2/time.Millisecond)) // ms: 100
尝试一下上面的例子去游乐场 https://play.golang.org/p/xLmj_Qzb81.
如果您的抖动(持续时间)小于您希望将其转换为的单位,则需要使用浮点除法,否则将执行整数除法,从而切除小数部分。详情请参阅:Golang 四舍五入到最接近的 0.05 https://stackoverflow.com/questions/39544571/golang-round-to-nearest-0-05/39544897#39544897.
将抖动和单位转换为float64
划分前:
d := 61 * time.Microsecond
fmt.Println(d) // Output: 61µs
ms := float64(d) / float64(time.Millisecond)
fmt.Println("ms:", ms) // Output: ms: 0.061
输出(尝试一下去游乐场 https://play.golang.org/p/mdB_JMw_zN):
61µs
ms: 0.061