pigfox
pigfox

Reputation: 1401

How to not round durations

I am attempting to clock the execution of a process and I need the value in seconds.

package main

import (
    "fmt"
    "time"
)

func main() {
    startTime := time.Now()
    time.Sleep(1379 * time.Millisecond)

    elapsedTime := time.Since(startTime)
    fmt.Println(elapsedTime) //->1.379s

    secs := float64(elapsedTime / time.Second)
    fmt.Println(secs)//->1
    //desired output is: 1.379
}

I am looking for a way to have the time not NOT being rounded. Here's the playground: https://play.golang.org/p/VLgKTpmkHPS

Upvotes: 0

Views: 128

Answers (2)

cslrnr
cslrnr

Reputation: 747

Epoc time to to convert the time to seconds

update : Below code works ?

package main

import (
    "fmt"
    "time"
)

func main() {
    startTime := time.Now()
    nanos := startTime.Unix()
    // fmt.Println(startTime)
    millis := nanos / 1000000
    elapsedInsecondsT := float64(millis)/float64(1000)
    fmt.Println( millis, elapsedInsecondsT )
}

courtesy : https://gobyexample.com/epoch

Upvotes: 0

Jonathan Hall
Jonathan Hall

Reputation: 79516

Just use the Seconds() method:

package main

import (
    "fmt"
    "time"
)

func main() {
    elapsedTime := 1379 * time.Millisecond
    fmt.Println(elapsedTime) //->1.379s

    secs := elapsedTime.Seconds()
    fmt.Println(secs)
}

playground.

Upvotes: 5

Related Questions