mirror of
https://github.com/zeromicro/go-zero.git
synced 2025-01-23 09:00:20 +08:00
chore: add more tests (#3261)
This commit is contained in:
parent
99ce24e2ab
commit
925cf8d3d1
@ -2,6 +2,8 @@ package prof
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@ -13,6 +15,10 @@ const (
|
|||||||
|
|
||||||
// DisplayStats prints the goroutine, memory, GC stats with given interval, default to 5 seconds.
|
// DisplayStats prints the goroutine, memory, GC stats with given interval, default to 5 seconds.
|
||||||
func DisplayStats(interval ...time.Duration) {
|
func DisplayStats(interval ...time.Duration) {
|
||||||
|
displayStatsWithWriter(os.Stdout, interval...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func displayStatsWithWriter(writer io.Writer, interval ...time.Duration) {
|
||||||
duration := defaultInterval
|
duration := defaultInterval
|
||||||
for _, val := range interval {
|
for _, val := range interval {
|
||||||
duration = val
|
duration = val
|
||||||
@ -24,7 +30,7 @@ func DisplayStats(interval ...time.Duration) {
|
|||||||
for range ticker.C {
|
for range ticker.C {
|
||||||
var m runtime.MemStats
|
var m runtime.MemStats
|
||||||
runtime.ReadMemStats(&m)
|
runtime.ReadMemStats(&m)
|
||||||
fmt.Printf("Goroutines: %d, Alloc: %vm, TotalAlloc: %vm, Sys: %vm, NumGC: %v\n",
|
fmt.Fprintf(writer, "Goroutines: %d, Alloc: %vm, TotalAlloc: %vm, Sys: %vm, NumGC: %v\n",
|
||||||
runtime.NumGoroutine(), m.Alloc/mega, m.TotalAlloc/mega, m.Sys/mega, m.NumGC)
|
runtime.NumGoroutine(), m.Alloc/mega, m.TotalAlloc/mega, m.Sys/mega, m.NumGC)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
36
core/prof/runtime_test.go
Normal file
36
core/prof/runtime_test.go
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
package prof
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDisplayStats(t *testing.T) {
|
||||||
|
writer := &threadSafeBuffer{
|
||||||
|
buf: strings.Builder{},
|
||||||
|
}
|
||||||
|
displayStatsWithWriter(writer, time.Millisecond*10)
|
||||||
|
time.Sleep(time.Millisecond * 50)
|
||||||
|
assert.Contains(t, writer.String(), "Goroutines: ")
|
||||||
|
}
|
||||||
|
|
||||||
|
type threadSafeBuffer struct {
|
||||||
|
buf strings.Builder
|
||||||
|
lock sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *threadSafeBuffer) String() string {
|
||||||
|
b.lock.Lock()
|
||||||
|
defer b.lock.Unlock()
|
||||||
|
return b.buf.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *threadSafeBuffer) Write(p []byte) (n int, err error) {
|
||||||
|
b.lock.Lock()
|
||||||
|
defer b.lock.Unlock()
|
||||||
|
return b.buf.Write(p)
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user