Skip to content

Instantly share code, notes, and snippets.

@vkuznecovas
Last active January 26, 2018 11:35
Show Gist options
  • Save vkuznecovas/5abf647f32e1d4b1c0f5d67274df274e to your computer and use it in GitHub Desktop.
Save vkuznecovas/5abf647f32e1d4b1c0f5d67274df274e to your computer and use it in GitHub Desktop.
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