Created
April 24, 2017 16:11
-
-
Save moehandi/4f414f26ac6b6ee0ab0aaf21522cd939 to your computer and use it in GitHub Desktop.
function for tracking time used by function
This file contains hidden or 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
package main | |
import ( | |
"time" | |
"fmt" | |
"log" | |
"runtime" | |
"github.com/fatih/color" | |
) | |
func timeTrack(start time.Time, funcName string) { | |
elapsed := time.Since(start) | |
coloredFunc := color.BlueString("%s", funcName) | |
coloredTime := color.RedString("%s", elapsed) | |
log.Printf("%s took: %s", coloredFunc, coloredTime) | |
} | |
func trace() string { | |
pc := make([]uintptr, 10) // at least 1 entry needed | |
runtime.Callers(2, pc) | |
f := runtime.FuncForPC(pc[0]) | |
file, line := f.FileLine(pc[0]) | |
//fmt.Printf("%s:%d %s\n", file, line, f.Name()) | |
return fmt.Sprintf("%s:%d %s", file, line, f.Name()) | |
} | |
func main() { | |
myFunc() | |
} | |
func myFunc() { | |
defer timeTrack(time.Now(), trace()) | |
i := 0 | |
for i < 1000000000 { // one billion | |
//fmt.Println("Myfunc") | |
i++ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment