Created
December 19, 2023 14:19
-
-
Save detj/05aa717a89ed6267526580baddd8ae6e to your computer and use it in GitHub Desktop.
measure go func execution time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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