登录
首页 >  Golang >  Go问答

能否测算Go应用程序的启动时间?

来源:stackoverflow

时间:2024-02-21 18:42:22 125浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《能否测算Go应用程序的启动时间?》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我尝试计算 go 应用程序启动和接受请求所需的时间。 我尝试使用以下方法来做到这一点:

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))
}

但是控制台只会打印在端口 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...

有没有办法显示正确的启动时间? 我所说的启动时间是指该应用程序开始侦听端口 8080 所需的时间。


正确答案


最简单的,对于大多数情况来说应该足够好了,是这样的:

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(...))
}

这可确保 start 在程序执行过程中尽早初始化,在其他包级变量之前以及在任何 init 函数之前初始化。然后,作为启动服务器之前的最后一件事,它会显示经过的时间。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《能否测算Go应用程序的启动时间?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>