Created
December 12, 2017 18:07
-
-
Save jonbodner/c37642f5d1e475b19824c2fb37ad6ef4 to your computer and use it in GitHub Desktop.
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
func MakeTimedFunction(f interface{}) interface{} { | |
rf := reflect.TypeOf(f) | |
if rf.Kind() != reflect.Func { | |
panic("expects a function") | |
} | |
vf := reflect.ValueOf(f) | |
wrapperF := reflect.MakeFunc(rf, func(in []reflect.Value) []reflect.Value { | |
start := time.Now() | |
out := vf.Call(in) | |
end := time.Now() | |
fmt.Printf("calling %s took %v\n", runtime.FuncForPC(vf.Pointer()).Name(), end.Sub(start)) | |
return out | |
}) | |
return wrapperF.Interface() | |
} | |
func timeMe() { | |
fmt.Println("starting") | |
time.Sleep(1 * time.Second) | |
fmt.Println("ending") | |
} | |
func timeMeToo(a int) int { | |
fmt.Println("starting") | |
time.Sleep(time.Duration(a) * time.Second) | |
result := a * 2 | |
fmt.Println("ending") | |
return result | |
} | |
func main() { | |
timed := MakeTimedFunction(timeMe).(func()) | |
timed() | |
timedToo := MakeTimedFunction(timeMeToo).(func(int) int) | |
fmt.Println(timedToo(2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment