-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfperf.go
42 lines (33 loc) · 828 Bytes
/
fperf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package fperf
import (
"reflect"
"runtime"
"time"
)
type ReportCallback func(name string, duration time.Duration)
func EmbedRunTimeMeasurement(f interface{}, report ReportCallback) interface{} {
rt := reflect.TypeOf(f)
if rt.Kind() != reflect.Func {
panic("f isn't a func")
}
tf := reflect.MakeFunc(rt, func(args []reflect.Value) (results []reflect.Value) {
rv := reflect.ValueOf(f)
name := runtime.FuncForPC(rv.Pointer()).Name()
start := time.Now()
results = rv.Call(args)
dur := time.Since(start)
report(name, dur)
return results
})
return tf.Interface()
}
func MeasureRunTime(report ReportCallback) func() {
name := "!unknown!"
if pc, _, _, ok := runtime.Caller(1); ok {
name = runtime.FuncForPC(pc).Name()
}
start := time.Now()
return func() {
report(name, time.Since(start))
}
}