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.

measurement.go 2.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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>", titlePart))
  39. }
  40. }
  41. }
  42. func (m *Measurement) Point(desc ...string) {
  43. if m == nil {
  44. return
  45. }
  46. if m.on {
  47. m.printer(m.makePointString(strings.Join(desc, ".")))
  48. }
  49. }
  50. func (m *Measurement) makePointString(desc string) string {
  51. last := m.lastPointTime
  52. now := time.Now()
  53. m.lastPointTime = now
  54. _, file, line, ok := runtime.Caller(2)
  55. titlePart := ""
  56. if m.title != "" {
  57. titlePart = fmt.Sprintf("(%s)", m.title)
  58. }
  59. if desc != "" {
  60. desc = fmt.Sprintf("@%s", desc)
  61. }
  62. if ok {
  63. return fmt.Sprintf("%v {%v/%v} %v<%v:%v>", titlePart, now.Sub(last), now.Sub(m.startTime), desc, path.Base(file), line)
  64. }
  65. return fmt.Sprintf("{%v/%v}%v<UNKNOWN>", now.Sub(last), now.Sub(m.startTime), desc)
  66. }
  67. func (m *Measurement) End(descs ...string) {
  68. if m == nil {
  69. return
  70. }
  71. if m.on {
  72. last := m.lastPointTime
  73. now := time.Now()
  74. m.lastPointTime = now
  75. _, file, line, ok := runtime.Caller(1)
  76. titlePart := ""
  77. if m.title != "" {
  78. titlePart = fmt.Sprintf(":%s", m.title)
  79. }
  80. desc := strings.Join(descs, ".")
  81. if desc != "" {
  82. desc = fmt.Sprintf("@%s", desc)
  83. }
  84. if ok {
  85. m.printer(fmt.Sprintf("[END%v] {%v/%v} %v<%v:%v>", titlePart, now.Sub(last), now.Sub(m.startTime), desc, path.Base(file), line))
  86. } else {
  87. m.printer(fmt.Sprintf("[END%v] {%v/%v} %v<UNKNOWN>", titlePart, now.Sub(last), now.Sub(m.startTime), desc))
  88. }
  89. }
  90. }