Skip to content

Commit

Permalink
perf: Improve push.RetentionPeriodToString() efficiency (#16252)
Browse files Browse the repository at this point in the history
Signed-off-by: Jordan Rushing <rushing.jordan@gmail.com>
  • Loading branch information
JordanRushing authored Feb 14, 2025
1 parent 9d926a1 commit 6e6658f
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 4 deletions.
8 changes: 4 additions & 4 deletions pkg/loghttp/push/push.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"math"
"mime"
"net/http"
"strconv"
"time"

"github.com/go-kit/log/level"
Expand Down Expand Up @@ -346,11 +347,10 @@ func ParseLokiRequest(userID string, r *http.Request, tenantsRetention TenantsRe
}

func RetentionPeriodToString(retentionPeriod time.Duration) string {
var retentionHours string
if retentionPeriod > 0 {
retentionHours = fmt.Sprintf("%d", int64(math.Floor(retentionPeriod.Hours())))
if retentionPeriod <= 0 {
return ""
}
return retentionHours
return strconv.FormatInt(int64(retentionPeriod/time.Hour), 10)
}

// OTLPError writes an OTLP-compliant error response to the given http.ResponseWriter.
Expand Down
87 changes: 87 additions & 0 deletions pkg/loghttp/push/push_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,93 @@ func Test_ServiceDetection(t *testing.T) {
})
}

func BenchmarkRetentionPeriodToString(b *testing.B) {
testCases := []struct {
name string
retentionPeriod time.Duration
}{
{
name: "744h",
retentionPeriod: 744 * time.Hour,
},
{
name: "840h",
retentionPeriod: 840 * time.Hour,
},
{
name: "2232h",
retentionPeriod: 2232 * time.Hour,
},
{
name: "8784h",
retentionPeriod: 8784 * time.Hour,
},
{
name: "1000h",
retentionPeriod: 1000 * time.Hour,
},
{
name: "zero retention period",
retentionPeriod: 0,
},
}

for _, tc := range testCases {
b.Run(tc.name, func(b *testing.B) {
b.ReportAllocs()
for n := 0; n < b.N; n++ {
RetentionPeriodToString(tc.retentionPeriod)
}
})
}
}

func TestRetentionPeriodToString(t *testing.T) {
testCases := []struct {
name string
retentionPeriod time.Duration
expected string
}{
{
name: "744h",
retentionPeriod: 744 * time.Hour,
expected: "744",
},
{
name: "840h",
retentionPeriod: 840 * time.Hour,
expected: "840",
},
{
name: "2232h",
retentionPeriod: 2232 * time.Hour,
expected: "2232",
},
{
name: "8784h",
retentionPeriod: 8784 * time.Hour,
expected: "8784",
},
{
name: "1000h",
retentionPeriod: 1000 * time.Hour,
expected: "1000",
},
{
name: "zero retention period",
retentionPeriod: 0,
expected: "",
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
actual := RetentionPeriodToString(tc.retentionPeriod)
assert.Equal(t, tc.expected, actual)
})
}
}

type fakeLimits struct {
enabled bool
labels []string
Expand Down

0 comments on commit 6e6658f

Please sign in to comment.