Conversion of time.Duration type microseconds value to milliseconds

后端 未结 3 2066
你的背包
你的背包 2020-12-01 07:41

I am using go-ping ( https://github.com/sparrc/go-ping )library of golang for unprivileged ICMP ping.

timeout := time.Second*1000
interval := time.Second
cou         


        
3条回答
  •  温柔的废话
    2020-12-01 08:06

    The type of latency and jitter variables is time.Duration which per definition its base type is int64 and is expressed in nanosecond.

    When you use print functions the String‍‍‍‍ ‍method of type time.Duration is invoked and it use h, s, m, µ, n notations when printing the duration, here is the documentation for String method:

    // String returns a string representing the duration in the form "72h3m0.5s".
    // Leading zero units are omitted. As a special case, durations less than one
    // second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure
    // that the leading digit is non-zero. The zero duration formats as 0s.
    

    There are some pre defined constants in time package which you can use to convert the duration variable to your preferred unit of time, like this:

    latencyInMicroSeconds := int64(jitter / time.Microsecond)
    

    Pay attention that we converted it to a int type because if you won't it would be still in time.Duration type and the value of that type is considered to be in nano second unit but now it's micro second which cause further problem in calculations if you're going to use time package functions.

提交回复
热议问题