You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test.go 1.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package time2
  2. import (
  3. "fmt"
  4. "path"
  5. "runtime"
  6. "strings"
  7. "time"
  8. )
  9. type Measurement struct {
  10. startTime time.Time
  11. lastPointTime time.Time
  12. printer func(string)
  13. on bool
  14. title string
  15. }
  16. func NewMeasurement(printer func(string)) Measurement {
  17. return Measurement{
  18. printer: printer,
  19. }
  20. }
  21. func (m *Measurement) Begin(on bool, title ...string) {
  22. if m == nil {
  23. return
  24. }
  25. m.on = on
  26. m.title = strings.Join(title, ".")
  27. if on {
  28. m.startTime = time.Now()
  29. m.lastPointTime = m.startTime
  30. _, file, line, ok := runtime.Caller(1)
  31. titlePart := ""
  32. if m.title != "" {
  33. titlePart = fmt.Sprintf(":%s", m.title)
  34. }
  35. if ok {
  36. m.printer(fmt.Sprintf("[begin%v]%v:%v", titlePart, path.Base(file), line))
  37. } else {
  38. m.printer(fmt.Sprintf("[begin%v]unknown point", titlePart))
  39. }
  40. }
  41. }
  42. func (m *Measurement) Point(head ...string) {
  43. if m == nil {
  44. return
  45. }
  46. if m.on {
  47. m.printer(m.makePointString(strings.Join(head, ".")))
  48. }
  49. }
  50. func (m *Measurement) makePointString(head string) string {
  51. last := m.lastPointTime
  52. now := time.Now()
  53. m.lastPointTime = now
  54. _, file, line, ok := runtime.Caller(2)
  55. prefixCont := ""
  56. if m.title != "" {
  57. prefixCont = m.title
  58. }
  59. if head != "" {
  60. if prefixCont == "" {
  61. prefixCont = head
  62. } else {
  63. prefixCont = fmt.Sprintf("%s.%s", prefixCont, head)
  64. }
  65. }
  66. prefixPart := ""
  67. if prefixCont != "" {
  68. prefixPart = fmt.Sprintf("[%s]", prefixCont)
  69. }
  70. if ok {
  71. return fmt.Sprintf("%v%v:%v@%v(%v)", prefixPart, path.Base(file), line, now.Sub(last), now.Sub(m.startTime))
  72. }
  73. return fmt.Sprintf("%vunknown point@%v(%v)", prefixPart, now.Sub(last), now.Sub(m.startTime))
  74. }
  75. func (m *Measurement) End(head ...string) {
  76. if m == nil {
  77. return
  78. }
  79. if m.on {
  80. m.printer(fmt.Sprintf("[end]%v\n", m.makePointString(strings.Join(head, "."))))
  81. }
  82. }