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 all 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
36 changes: 33 additions & 3 deletions backend/gtime/gtime.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gtime

import (
"errors"
"fmt"
"regexp"
"strconv"
Expand Down Expand Up @@ -74,18 +75,47 @@ func ParseDuration(inp string) (time.Duration, error) {
}

func parse(inp string) (time.Duration, string, error) {
result := dateUnitPattern.FindSubmatch([]byte(inp))
if inp == "" {
return 0, "", backend.DownstreamError(errors.New("empty input"))
}

// Fast path for simple duration formats (no date units)
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
25 changes: 25 additions & 0 deletions backend/gtime/gtime_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,30 @@ 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)
}
})
}
}

// go test -benchmem -run=^$ -bench=BenchmarkParseIntervalStringToTimeDuration$ github.
// com/grafana/grafana-plugin-sdk-go/backend/gtime/ -memprofile p_mem.out -count 6 | tee p_mem.txt
func BenchmarkParseIntervalStringToTimeDuration(b *testing.B) {
Expand All @@ -26,6 +50,7 @@ func BenchmarkParseIntervalStringToTimeDuration(b *testing.B) {
for _, tc := range testCases {
b.Run(tc.name, func(b *testing.B) {
for i := 0; i < b.N; i++ {
b.ResetTimer()
_, err := ParseIntervalStringToTimeDuration(tc.interval)
if err != nil {
b.Fatal(err)
Expand Down
122 changes: 122 additions & 0 deletions backend/gtime/gtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,125 @@ 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(`empty input`),
},
{
name: "fast path - pure number with date unit",
input: "30d",
wantDur: 30,
wantPeriod: "d",
},
{
name: "fast path - pure number with week unit",
input: "2w",
wantDur: 2,
wantPeriod: "w",
},
{
name: "fast path - pure number with month unit",
input: "6M",
wantDur: 6,
wantPeriod: "M",
},
{
name: "fast path - pure number with year unit",
input: "5y",
wantDur: 5,
wantPeriod: "y",
},
{
name: "non-numeric prefix with date unit",
input: "a5d",
wantErrRegex: regexp.MustCompile(`time: invalid duration "?a5d"?`),
},
{
name: "mixed characters with date unit",
input: "5a3d",
wantErrRegex: regexp.MustCompile(`time: unknown unit "a" in duration "5a3d"`),
},
}

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)
})
}
}