能否测算Go应用程序的启动时间?
时间:2024-02-21
浏览: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学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.30
11.30
11.29
11.29
11.29
热门专题
