Skip to content

Instantly share code, notes, and snippets.

@moehandi
Created April 24, 2017 16:11
Show Gist options
  • Save moehandi/4f414f26ac6b6ee0ab0aaf21522cd939 to your computer and use it in GitHub Desktop.
Save moehandi/4f414f26ac6b6ee0ab0aaf21522cd939 to your computer and use it in GitHub Desktop.
function for tracking time used by function
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