This repository has been archived by the owner on Feb 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
observation.go
73 lines (63 loc) · 1.44 KB
/
observation.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package labassistant
import (
"fmt"
"reflect"
"runtime"
"time"
)
type Observation struct {
Name string
Panic interface{}
Outputs []interface{}
Start time.Time
Duration time.Duration
Mismatch bool
fun interface{}
can_panic bool
}
// Try to run the function for an observation, and if successful, set some stats.
func (ob *Observation) run(f interface{}, args ...interface{}) []interface{} {
fv := reflect.ValueOf(f)
if len(ob.Name) == 0 {
if rf := runtime.FuncForPC(fv.Pointer()); rf != nil {
ob.Name = rf.Name()
}
}
fvtype := fv.Type()
if len(args) != fvtype.NumIn() {
panic(fmt.Errorf("Incorrect number of inputs to %v", ob.Name))
}
inputs := []reflect.Value{}
for i, a := range args {
tmp := reflect.ValueOf(a)
tmptype := tmp.Type()
in := fvtype.In(i)
if tmptype != in {
panic(fmt.Errorf("Invalid input (%v) to function (expected %v)",
tmptype.Kind(),
in.Kind(),
))
}
inputs = append(inputs, tmp)
}
ret := ob.make_call(fv, inputs)
if ob.Panic != nil {
return nil
}
for _, r := range ret {
ob.Outputs = append(ob.Outputs, r.Interface())
}
return ob.Outputs
}
// Do the actual call to the function and make some measurements.
func (ob *Observation) make_call(fv reflect.Value, inputs []reflect.Value) []reflect.Value {
if ob.can_panic {
defer func() {
ob.Panic = recover()
}()
}
ob.Start = time.Now()
ret := fv.Call(inputs)
ob.Duration = time.Since(ob.Start)
return ret
}