Özg*_*çın 15 go execution-time
我正在寻找计算执行时间的最佳方法.
func main() {
start := time.Now()
time.Sleep(time.Second * 2)
//something doing here
elapsed := time.Since(start)
fmt.Printf("page took %s", elapsed)
}
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常.
但是当我使用模板时,我必须为每个模板函数再次编写它.
有没有一种有效的方法来计算执行时间,包括模板?
Cer*_*món 39
如果您要对整个函数进行计时,那么您可以使用它defer
来消除一些重复的代码.
func elapsed(what string) func() {
start := time.Now()
return func() {
fmt.Printf("%s took %v\n", what, time.Since(start))
}
}
func main() {
defer elapsed("page")() // <-- The trailing () is the deferred call
time.Sleep(time.Second * 2)
}
Run Code Online (Sandbox Code Playgroud)
Cerise提供的解决方案非常完美.
另外,如果你不想显式传递函数名,你可以像这样完成它:
func SomeFunction(list *[]string) {
defer TimeTrack(time.Now())
// Do whatever you want.
}
func TimeTrack(start time.Time) {
elapsed := time.Since(start)
// Skip this function, and fetch the PC and file for its parent.
pc, _, _, _ := runtime.Caller(1)
// Retrieve a function object this functions parent.
funcObj := runtime.FuncForPC(pc)
// Regex to extract just the function name (and not the module path).
runtimeFunc := regexp.MustCompile(`^.*\.(.*)$`)
name := runtimeFunc.ReplaceAllString(funcObj.Name(), "$1")
log.Println(fmt.Sprintf("%s took %s", name, elapsed))
}
Run Code Online (Sandbox Code Playgroud)
结果,你会得到:
SomeFunction took 15.483µs
有关更多信息,请参阅此文章:Go Function Tracing
分享知识.:)
使用初始化函数
package main
import (
"fmt"
"time"
)
var start time.Time
func init() {
start = time.Now()
}
func getChars(s string) {
for _, c := range s {
fmt.Printf("%c at time %v\n", c, time.Since(start))
time.Sleep(10 * time.Millisecond)
}
}
func main() {
fmt.Println("main execution started at time", time.Since(start))
getChars("Hello")
fmt.Println("\nmain execution stopped at time", time.Since(start))
}
Run Code Online (Sandbox Code Playgroud)