How to initialize a constant with the value of time. Now() in Golang?

Asked

Viewed 177 times

-6

I’m used to doing projects in Python where, when initializing the same I keep a variable saying when it started (to measure the execution time of the project) like this:

import time
started_at = time.perf_counter()

So at the end of the code I can calculate the difference between the started_at and a new time.perf_counter() and know the execution time of the code.

I’m starting to study Golang now and, while trying to do the same thing is appearing an error message "const initializer &time. Now() is not a Constant" . Follow the code I started building:

package app

import "time"

const startedAt = time.Now()

What I need to do in order to have the same behavior as the first code in Golang?

3 answers

5

do Python projects where, when initializing the same I save a variable

I highlighted the word variable. I can’t imagine why you tried to use a Go constant if in Python you used a variable, if you want to do the same then write a compatible code, do not enter another semantics.

A constant must be a value that will never change. A time is the perfect definition of something that changes, it is impossible to take the same data in two executions.

It seems to believe that constant is a variable that does not change its value and this is not correct. To better understand: Constant is really useful? (follow the links).

What I need to do in order to have the same behavior as the first code in Golang?

Keep data as a variable. Only swap const for var or assign with :=.

If you want an immutable variable, Go, today, doesn’t have it, just like Python doesn’t have not even constant.

I don’t think only this will make the behavior of the Python code happen in Go, after Python is using a performance analysis library and in Go is using a library that works with normal hours. I know it’s intuitive to think that you just take the time you started and finish the operation, subtract from each other and you know how long it took, but these time libraries don’t usually have enough resolution and accuracy to deliver reliable results for performance analytics.

As far as I know if you do this with go test, then why reinvent the wheel?

Caminhonete com rodas quadradas

2


To have the same behavior you should use var and not const:

package app

import "time"

var startedAt = time.Now()

When the variable is inside a function it is also possible to use the := to create the variable (such as startedAt := time.Now()).


Golang does not allow using functions as a constant. This is for everything, even what is in theory constant. Just as you cannot use const v = time.Now(), you can’t use const v = math.Abs(1.2).


Every rule has exceptions, there are few functions that can be used as const, most of them belong to the unsafe, that the name itself already gives a hint of what it is about. In addition to some functions (and in some cases) that are already of the language itself (with the len).

If it is see the documentation of unfsafe, you may notice the comment:

// The Return value of Alignof is a Go Constant.

Then it is possible to use a const c = unsafe.Sizeof([]int{}). You can also use const c = len("abc"), but you can’t use len([]int{1,2,3}), since Slice are not constant.

  • Simple, direct and exactly what I needed to know about the "why" not working. Thank you very much.

0

Because you want to count the time, I found it laborious your way, for my projects I use this method:

package main

import (
    "fmt"
    "time"
)

var end chan bool
var tsecs chan string

func init() {
    end = make(chan bool)
    tsecs = make(chan string)
}

func main() {
    go contador()

    //exemplo de código executando!
    time.Sleep(10 * time.Second)

    //encerrar
    end <- true
    res := <-tsecs
    fmt.Printf("%s seconds", res)
}

func contador() {
    var seconds int = 0
    for {
        time.Sleep(time.Second)
        seconds++
        select {
        case <-end:
            tsecs <- fmt.Sprintf("%d", seconds)
            break
        default:
            continue
        }
    }
}

In charge of GOROUTINE count, in my case I am counting the seconds, but it is possible to change to smaller units by modifying the team. Sleep()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.