Explorar el Código

Add profile logging util

Niko Kovacevic hace 4 años
padre
commit
fcbc37fa6b
Se han modificado 2 ficheros con 111 adiciones y 0 borrados
  1. 59 0
      pkg/util/timeutil/profile.go
  2. 52 0
      pkg/util/timeutil/profile_test.go

+ 59 - 0
pkg/util/timeutil/profile.go

@@ -0,0 +1,59 @@
+package timeutil
+
+import (
+	"fmt"
+	"strings"
+	"time"
+)
+
+type ProfileDataSeries struct {
+	Name   string
+	Series []*ProfileDatum
+}
+
+func NewProfileDataSeries(name string, steps int) *ProfileDataSeries {
+	return &ProfileDataSeries{
+		Name:   name,
+		Series: make([]*ProfileDatum, 0, steps+2),
+	}
+}
+
+func (pds *ProfileDataSeries) Start() {
+	pds.Series = append(pds.Series, &ProfileDatum{
+		Name: "start",
+		Time: time.Now().UTC(),
+	})
+}
+
+func (pds *ProfileDataSeries) Step(name string) {
+	pds.Series = append(pds.Series, &ProfileDatum{
+		Name: name,
+		Time: time.Now().UTC(),
+	})
+}
+
+func (pds *ProfileDataSeries) Stop() {
+	pds.Series = append(pds.Series, &ProfileDatum{
+		Name: "stop",
+		Time: time.Now().UTC(),
+	})
+}
+
+func (pds *ProfileDataSeries) String() string {
+	if pds == nil || len(pds.Series) < 2 {
+		return "--"
+	}
+
+	var sb strings.Builder
+	sb.WriteString(fmt.Sprintf("%s %v", pds.Name, pds.Series[len(pds.Series)-1].Time.Sub(pds.Series[0].Time)))
+	for i := 1; i < len(pds.Series); i++ {
+		pd := pds.Series[i]
+		sb.WriteString(fmt.Sprintf(" [%s %v]", pd.Name, pds.Series[i].Time.Sub(pds.Series[i-1].Time)))
+	}
+	return sb.String()
+}
+
+type ProfileDatum struct {
+	Name string
+	Time time.Time
+}

+ 52 - 0
pkg/util/timeutil/profile_test.go

@@ -0,0 +1,52 @@
+package timeutil
+
+import (
+	"fmt"
+	"testing"
+	"time"
+)
+
+func TestProfileDataSeries_NilOrZero(t *testing.T) {
+	pds1 := NewProfileDataSeries("test1", 0)
+	fmt.Println(pds1.String())
+
+	pds2 := NewProfileDataSeries("test2", 0)
+	pds2.Start()
+	fmt.Println(pds2.String())
+
+	pds2.Stop()
+	fmt.Println(pds2.String())
+}
+
+func TestProfileDataSeries_Series(t *testing.T) {
+	pds := NewProfileDataSeries("test", 3)
+
+	pds.Start()
+
+	time.Sleep(10 * time.Millisecond)
+
+	pds.Step("step1")
+
+	time.Sleep(100 * time.Millisecond)
+
+	pds.Step("step2")
+
+	time.Sleep(5 * time.Millisecond)
+
+	pds.Step("step3")
+
+	time.Sleep(1 * time.Millisecond)
+
+	pds.Stop()
+
+	fmt.Println(len(pds.Series))
+	for i, p := range pds.Series {
+		if p == nil {
+			fmt.Printf("%d nil\n", i)
+		} else {
+			fmt.Printf("%d %s %v\n", i, p.Name, p.Time)
+		}
+	}
+
+	fmt.Println(pds.String())
+}