Skip to content

Instantly share code, notes, and snippets.

@detj
Created December 19, 2023 14:19
Show Gist options
  • Save detj/05aa717a89ed6267526580baddd8ae6e to your computer and use it in GitHub Desktop.
Save detj/05aa717a89ed6267526580baddd8ae6e to your computer and use it in GitHub Desktop.
measure go func execution time
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))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment