forked from zhemao/glisp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timing.go
63 lines (52 loc) · 1.3 KB
/
timing.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
package glispext
import (
"errors"
"fmt"
"github.com/zhemao/glisp/interpreter"
"time"
)
type SexpTime time.Time
func (t SexpTime) SexpString() string {
return time.Time(t).String()
}
func TimeFunction(env *glisp.Glisp, name string,
args []glisp.Sexp) (glisp.Sexp, error) {
return SexpTime(time.Now()), nil
}
func TimeitFunction(env *glisp.Glisp, name string,
args []glisp.Sexp) (glisp.Sexp, error) {
if len(args) != 1 {
return glisp.SexpNull, glisp.WrongNargs
}
var fun glisp.SexpFunction
switch t := args[0].(type) {
case glisp.SexpFunction:
fun = t
default:
return glisp.SexpNull,
errors.New("argument of timeit should be function")
}
starttime := time.Now()
elapsed := time.Since(starttime)
maxseconds := 10.0
var iterations int
for iterations = 0; iterations < 10000; iterations++ {
_, err := env.Apply(fun, []glisp.Sexp{})
if err != nil {
return glisp.SexpNull, err
}
elapsed = time.Since(starttime)
if elapsed.Seconds() > maxseconds {
break
}
}
fmt.Printf("ran %d iterations in %f seconds\n",
iterations, elapsed.Seconds())
fmt.Printf("average %f seconds per run\n",
elapsed.Seconds()/float64(iterations))
return glisp.SexpNull, nil
}
func ImportTime(env *glisp.Glisp) {
env.AddFunction("time", TimeFunction)
env.AddFunction("timeit", TimeitFunction)
}