编号为 time.Duration
time.Duration是具有
int64作为其基础类型的类型,该类型存储持续时间(以纳秒为单位)。
如果您知道该值,但想要的不是纳秒,则只需乘以所需的单位,例如:
d := 100 * time.Microsecondfmt.Println(d) // Output: 100µs
上面的方法是有效的,因为它
100是一个无类型的常量,并且可以自动将
time.Duration其转换为具有
int64基础类型的常量。
请注意,如果您将该值作为类型化值,则必须使用显式类型转换:
value := 100 // value is of type intd2 := time.Duration(value) * time.Millisecondfmt.Println(d2) // Output: 100ms
time.Duration
编号
所以
time.Duration总是纳秒。例如,如果您需要以毫秒为单位,则只需将
time.Duration值除以毫秒内的纳秒数即可:
ms := int64(d2 / time.Millisecond)fmt.Println("ms:", ms) // Output: ms: 100其他例子:
fmt.Println("ns:", int64(d2/time.Nanosecond)) // ns: 100000000fmt.Println("µs:", int64(d2/time.Microsecond)) // µs: 100000fmt.Println("ms:", int64(d2/time.Millisecond)) // ms: 100在Go Playground上尝试示例。
如果您的抖动(持续时间)小于您希望将其转换为的单位,则需要使用浮点除法,否则将执行整数除法,以切除小数部分。
float64在除法之前将抖动和单位都转换为:
d := 61 * time.Microsecondfmt.Println(d) // Output: 61µsms := float64(d) / float64(time.Millisecond)fmt.Println("ms:", ms) // Output: ms: 0.061输出(在Go Playground上尝试):
61µsms: 0.061



