Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

backend: improve parse function performance in gtime package #1238

Merged
merged 6 commits into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 30 additions & 3 deletions backend/gtime/gtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,45 @@ func ParseDuration(inp string) (time.Duration, error) {
}

func parse(inp string) (time.Duration, string, error) {
result := dateUnitPattern.FindSubmatch([]byte(inp))
// Fast path for simple duration formats (no date units)
if len(inp) > 0 {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be:

  if inp == "" {
    return 0, "", errors.New("empty input")
  }

then the following code can come out of the if block.

lastChar := inp[len(inp)-1]
if lastChar != 'd' && lastChar != 'w' && lastChar != 'M' && lastChar != 'y' {
dur, err := time.ParseDuration(inp)
return dur, "", err
}

// Check if the rest is a number for date units
numPart := inp[:len(inp)-1]
isNum := true
for _, c := range numPart {
if c < '0' || c > '9' {
isNum = false
break
}
}
if isNum {
num, err := strconv.Atoi(numPart)
if err != nil {
return 0, "", err
}
return time.Duration(num), string(lastChar), nil
}
}

// Fallback to regex for complex cases
result := dateUnitPattern.FindStringSubmatch(inp)
if len(result) != 3 {
dur, err := time.ParseDuration(inp)
return dur, "", err
}

num, err := strconv.Atoi(string(result[1]))
num, err := strconv.Atoi(result[1])
if err != nil {
return 0, "", err
}

return time.Duration(num), string(result[2]), nil
return time.Duration(num), result[2], nil
}

// FormatInterval converts a duration into the units that Grafana uses
Expand Down
29 changes: 29 additions & 0 deletions backend/gtime/gtime_bench_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package gtime

import (
"testing"
)

// go test -benchmem -run=^$ -bench=BenchmarkParse$ github.com/grafana/grafana-plugin-sdk-go/backend/gtime/ -memprofile p_mem.out -count 6 | tee pmem.0.txt
func BenchmarkParse(b *testing.B) {
testCases := []struct {
name string
input string
}{
{"PureNumber", "30"},
{"SimpleUnit", "5s"},
{"ComplexUnit", "1h30m"},
{"DateUnit", "7d"},
{"MonthUnit", "3M"},
{"YearUnit", "1y"},
}

for _, tc := range testCases {
b.Run(tc.name, func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _, _ = parse(tc.input)
}
})
}
}
88 changes: 88 additions & 0 deletions backend/gtime/gtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,91 @@ func TestRoundInterval(t *testing.T) {
})
}
}

func TestParse(t *testing.T) {
tests := []struct {
name string
input string
wantDur time.Duration
wantPeriod string
wantErrRegex *regexp.Regexp
}{
{
name: "simple duration seconds",
input: "30s",
wantDur: 30 * time.Second,
wantPeriod: "",
},
{
name: "simple duration minutes",
input: "5m",
wantDur: 5 * time.Minute,
wantPeriod: "",
},
{
name: "simple duration minutes and seconds",
input: "1m30s",
wantDur: 90 * time.Second,
wantPeriod: "",
},
{
name: "complex duration",
input: "1h30m",
wantDur: 90 * time.Minute,
wantPeriod: "",
},
{
name: "days unit",
input: "7d",
wantDur: 7,
wantPeriod: "d",
},
{
name: "weeks unit",
input: "2w",
wantDur: 2,
wantPeriod: "w",
},
{
name: "months unit",
input: "3M",
wantDur: 3,
wantPeriod: "M",
},
{
name: "years unit",
input: "1y",
wantDur: 1,
wantPeriod: "y",
},
{
name: "invalid duration",
input: "invalid",
wantErrRegex: regexp.MustCompile(`time: invalid duration "?invalid"?`),
},
{
name: "invalid number",
input: "abc1d",
wantErrRegex: regexp.MustCompile(`time: invalid duration "?abc1d"?`),
},
{
name: "empty string",
input: "",
wantErrRegex: regexp.MustCompile(`time: invalid duration "?"`),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotDur, gotPeriod, err := parse(tt.input)
if tt.wantErrRegex != nil {
require.Error(t, err)
require.Regexp(t, tt.wantErrRegex, err.Error())
return
}
require.NoError(t, err)
require.Equal(t, tt.wantDur, gotDur)
require.Equal(t, tt.wantPeriod, gotPeriod)
})
}
}