-
-
Save vkuznecovas/5abf647f32e1d4b1c0f5d67274df274e to your computer and use it in GitHub Desktop.
defer use case
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" | |
"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