Atu*_*lya -2 testing performance go performance-testing
我尝试计算 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))
}
Run Code Online (Sandbox Code Playgroud)
但控制台只打印直到 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...
Run Code Online (Sandbox Code Playgroud)
有没有办法显示正确的启动时间?我所说的启动时间是指该应用程序开始侦听端口 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(...))
}
Run Code Online (Sandbox Code Playgroud)
这确保了start
在程序执行过程中尽早初始化,在其他包级变量之前以及在任何init
函数之前初始化。然后,作为启动服务器之前的最后一件事,它会显示经过的时间。