优化代码

This commit is contained in:
刘祥超
2022-03-20 10:48:11 +08:00
parent d45254b46d
commit c86f2d5a44
2 changed files with 51 additions and 3 deletions

View File

@@ -1,15 +1,18 @@
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved. // Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package nodes package nodes_test
import ( import (
"bytes" "bytes"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeNode/internal/nodes"
"github.com/TeaOSLab/EdgeNode/internal/rpc" "github.com/TeaOSLab/EdgeNode/internal/rpc"
"github.com/TeaOSLab/EdgeNode/internal/utils/testutils"
_ "github.com/iwind/TeaGo/bootstrap" _ "github.com/iwind/TeaGo/bootstrap"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
"reflect" "reflect"
"runtime" "runtime"
"runtime/debug"
"strconv" "strconv"
"strings" "strings"
"testing" "testing"
@@ -47,7 +50,7 @@ func TestHTTPAccessLogQueue_Push(t *testing.T) {
}, },
} }
new(HTTPAccessLogQueue).toValidUTF8(accessLog) new(nodes.HTTPAccessLogQueue).ToValidUTF8(accessLog)
// logs.PrintAsJSON(accessLog) // logs.PrintAsJSON(accessLog)
@@ -105,6 +108,33 @@ func TestHTTPAccessLogQueue_Push2(t *testing.T) {
t.Log("ok") t.Log("ok")
} }
func TestHTTPAccessLogQueue_Memory(t *testing.T) {
testutils.StartMemoryStats(t)
debug.SetGCPercent(10)
var accessLogs = []*pb.HTTPAccessLog{}
for i := 0; i < 20_000; i++ {
accessLogs = append(accessLogs, &pb.HTTPAccessLog{
RequestPath: "https://goedge.cn/hello/world",
})
}
runtime.GC()
// will not release automatically
func() {
var accessLogs1 = []*pb.HTTPAccessLog{}
for i := 0; i < 2_000_000; i++ {
accessLogs1 = append(accessLogs1, &pb.HTTPAccessLog{
RequestPath: "https://goedge.cn/hello/world",
})
}
}()
time.Sleep(5 * time.Second)
}
func BenchmarkHTTPAccessLogQueue_ToValidUTF8(b *testing.B) { func BenchmarkHTTPAccessLogQueue_ToValidUTF8(b *testing.B) {
runtime.GOMAXPROCS(1) runtime.GOMAXPROCS(1)

View File

@@ -10,7 +10,7 @@ import (
"time" "time"
) )
func StartMemoryStats(t *testing.T) { func StartMemoryStatsGC(t *testing.T) {
var ticker = time.NewTicker(1 * time.Second) var ticker = time.NewTicker(1 * time.Second)
go func() { go func() {
var stat = &runtime.MemStats{} var stat = &runtime.MemStats{}
@@ -31,3 +31,21 @@ func StartMemoryStats(t *testing.T) {
} }
}() }()
} }
func StartMemoryStats(t *testing.T) {
var ticker = time.NewTicker(1 * time.Second)
go func() {
var stat = &runtime.MemStats{}
var lastHeapInUse uint64
for range ticker.C {
runtime.ReadMemStats(stat)
if stat.HeapInuse == lastHeapInUse {
return
}
lastHeapInUse = stat.HeapInuse
t.Log(timeutil.Format("H:i:s"), "HeapInuse:", fmt.Sprintf("%.2fM", float64(stat.HeapInuse)/1024/1024), "NumGC:", stat.NumGC)
}
}()
}