Skip to content

Instantly share code, notes, and snippets.

@phuslu
Last active January 23, 2024 10:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phuslu/0ee71ce42e38d13c1fed76e182ddce56 to your computer and use it in GitHub Desktop.
Save phuslu/0ee71ce42e38d13c1fed76e182ddce56 to your computer and use it in GitHub Desktop.
fast parse DeletionTimestamp from pod
package bench
import (
"testing"
)
func BenchmarkParseDeletionTimestamp(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = ParseDeletionTimestamp(data)
}
}
package bench
import (
"fmt"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/VictoriaMetrics/easyproto"
)
func ParseDeletionTimestamp(data []byte) (ts int64, err error) {
var fc easyproto.FieldContext
var ok bool
for len(data) > 0 {
data, err = fc.NextField(data)
if err != nil {
return 0, fmt.Errorf("cannot read next field in Pod message")
}
switch fc.FieldNum {
case 1:
data, ok = fc.MessageData()
if !ok {
return 0, fmt.Errorf("cannot read Pod ObjectMeta name")
}
for len(data) > 0 {
data, err = fc.NextField(data)
if err != nil {
return 0, fmt.Errorf("cannot read next field in Pod ObjectMeta message")
}
switch fc.FieldNum {
case 9:
data, ok := fc.MessageData()
if !ok {
return 0, fmt.Errorf("cannot read Pod DeletionTimestamp name")
}
for len(data) > 0 {
data, err = fc.NextField(data)
if !ok {
return 0, fmt.Errorf("cannot read Pod DeletionTimestamp name")
}
switch fc.FieldNum {
case 1:
ts, ok = fc.Int64()
if !ok {
return 0, fmt.Errorf("cannot read Pod DeletionTimestamp name")
}
return
}
}
}
}
}
}
return
}
var pod, data = func() (*corev1.Pod, []byte) {
now := metav1.Now()
pod := &corev1.Pod{}
pod.Name = "test"
pod.DeletionTimestamp = &now
// pod.DeletionTimestamp = nil
data, _ := pod.Marshal()
return pod, data
}()
func main() {
deletionTimestamp, err := ParseDeletionTimestamp(data)
fmt.Printf("pod deletionTimestamp=%#v err=%v\n", deletionTimestamp, err)
}
goos: windows
goarch: amd64
pkg: bench
cpu: 11th Gen Intel(R) Core(TM) i7-1185G7 @ 3.00GHz
BenchmarkParseDeletionTimestamp
BenchmarkParseDeletionTimestamp-8 20026668 51.21 ns/op 0 B/op 0 allocs/op
PASS
ok bench 2.085s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment