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
count := 5
host := p.ipAddr
pinger, cmdErr := ping.NewPinger(host)
pinger.Count = count
pinger.Interval = interval
pinger.Timeout = timeout
pinger.SetPrivileged(false)
pinger.Run()
stats := pinger.Statistics()
latency = stats.AvgRtt // stats.AvgRtt is time.Duration type
jitter = stats.StdDevRtt// stats.StdDevRtt is time.Duration type
From running this, I am getting latency in milliseconds and jitter in microseconds. I want same unit for both let's say millisecond so when I am doing jitter = stats.StdDevRtt/1000
or jitter = jitter/1000
(to convert microseconds to milliseconds), what I am getting is jitter in nanoseconds :(. Is there any way to get same unit milliseconds for both latency and jitter.
Number to
time.Duration
time.Duration
is a type havingint64
as its underlying type, which stores the duration in nanoseconds.If you know the value but you want other than nanoseconds, simply multiply the unit you want, e.g.:
The above works because
100
is an untyped constant, and it can be converted automatically totime.Duration
which hasint64
underlying type.Note that if you have the value as a typed value, you have to use explicit type conversion:
time.Duration
to numberSo
time.Duration
is always the nanoseconds. If you need it in milliseconds for example, all you need to do is divide thetime.Duration
value with the number of nanoseconds in a millisecond:Other examples:
Try the examples on the Go Playground.
If your jitter (duration) is less than the unit you whish to convert it to, you need to use floating point division, else an integer division will be performed which cuts off the fraction part. For details see: Golang Round to Nearest 0.05.
Convert both the jitter and unit to
float64
before dividing:Output (try it on the Go Playground):
As of Go 1.13, you can use new Duration methods
Microseconds
andMilliseconds
which return the duration as an integer count of their respectively named units.https://golang.org/doc/go1.13#time
The type of
latency
andjitter
variables istime.Duration
which per definition its base type is int64 and is expressed in nanosecond.When you use print functions the
String
method of typetime.Duration
is invoked and it useh
,s
,m
,µ
,n
notations when printing the duration, here is the documentation forString
method: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:
Pay attention that we converted it to a
int
type because if you won't it would be still intime.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.