timing.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package glispext
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/zhemao/glisp/interpreter"
  6. "time"
  7. )
  8. type SexpTime time.Time
  9. func (t SexpTime) SexpString() string {
  10. return time.Time(t).String()
  11. }
  12. func TimeFunction(env *glisp.Glisp, name string,
  13. args []glisp.Sexp) (glisp.Sexp, error) {
  14. return SexpTime(time.Now()), nil
  15. }
  16. func TimeitFunction(env *glisp.Glisp, name string,
  17. args []glisp.Sexp) (glisp.Sexp, error) {
  18. if len(args) != 1 {
  19. return glisp.SexpNull, glisp.WrongNargs
  20. }
  21. var fun glisp.SexpFunction
  22. switch t := args[0].(type) {
  23. case glisp.SexpFunction:
  24. fun = t
  25. default:
  26. return glisp.SexpNull,
  27. errors.New("argument of timeit should be function")
  28. }
  29. starttime := time.Now()
  30. elapsed := time.Since(starttime)
  31. maxseconds := 10.0
  32. var iterations int
  33. for iterations = 0; iterations < 10000; iterations++ {
  34. _, err := env.Apply(fun, []glisp.Sexp{})
  35. if err != nil {
  36. return glisp.SexpNull, err
  37. }
  38. elapsed = time.Since(starttime)
  39. if elapsed.Seconds() > maxseconds {
  40. break
  41. }
  42. }
  43. fmt.Printf("ran %d iterations in %f seconds\n",
  44. iterations, elapsed.Seconds())
  45. fmt.Printf("average %f seconds per run\n",
  46. elapsed.Seconds()/float64(iterations))
  47. return glisp.SexpNull, nil
  48. }
  49. func ImportTime(env *glisp.Glisp) {
  50. env.AddFunction("time", TimeFunction)
  51. env.AddFunction("timeit", TimeitFunction)
  52. }