Instantly share code, notes, and snippets.

@vkuznecovas vkuznecovas/main.go Secret
Last active Jan 26, 2018

Embed
What would you like to do?
defer use case
package main
import (
"time"
"fmt"
"runtime"
)
type Timer struct {
start time.Time
defaultValue string
}
func New() *Timer {
return &Timer{
start: time.Now(),
defaultValue: "{unknown}",
}
}
func (t *Timer) End() {
callerName := t.GetCallerName()
if callerName == nil {
callerName = &t.defaultValue
}
fmt.Printf("Execution of %v took %v", *callerName, time.Since(t.start))
}
func (t *Timer) GetCallerName() (name *string) {
uintpt := make([]uintptr, 1)
n := runtime.Callers(3, uintpt)
if n == 0 {
return
}
fun := runtime.FuncForPC(uintpt[0]-1)
if fun == nil {
return
}
nameTemp := fun.Name()
name = &nameTemp
return
}
func main() {
defer New().End()
fmt.Println("Sleeping!")
time.Sleep(time.Nanosecond * 100)
fmt.Println("Well slept!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment