Search code examples
performancegotestingperformance-testing

Is there any way to calculate the startup time of Go app?


I tried to calculate the time a Go app takes to start up and accept requests. I tried to do it using:

func main() {
    start:=time.Now()
    repo.CreateConnection()
    router := mux.NewRouter()
    r := bookController.Controller(router)
    fmt.Println("Starting server on the port 8080...")
    log.Fatal(http.ListenAndServe(":8080", r))
    fmt.Println(time.Since(start))
}

But the console only prints till Starting server on the port 8080...

GOROOT=/usr/local/go #gosetup
GOPATH=/Users/admin/go #gosetup
/usr/local/go/bin/go build -o /private/var/folders/t3/1fk2w7y55qs1dfxbxbvpsn9h0000gp/T/___go_build_payments_go_performance go-performance #gosetup
/private/var/folders/t3/1fk2w7y55qs1dfxbxbvpsn9h0000gp/T/___go_build_go_performance
Successfully connected!
Starting server on the port 8080...

Is there anyway to display the correct startup time? By startup time, I mean the time this app take to starts listening to port 8080.


Solution

  • The easiest, which should be good enough for most cases, would be something like this:

    package main
    
    var start = time.Now()
    
    /* place any other package variable declarations after `start` */
    
    func main() {
        /* set up code */
        fmt.Printf("Startup took aprox %v\n", time.Since(start))
        log.Fatal(http.ListenAndServe(...))
    }
    

    This ensures that start is initialized as early as possible in the execution of your program, before other package-level variables, and before any init functions. Then as the very last thing before launching the server, it displays the elapsed time.