Skip to content

Instantly share code, notes, and snippets.

@changkun
Created August 7, 2018 08:27
Show Gist options
  • Select an option

  • Save changkun/3345491b4dd3919ed802068f9a8ceb3b to your computer and use it in GitHub Desktop.

Select an option

Save changkun/3345491b4dd3919ed802068f9a8ceb3b to your computer and use it in GitHub Desktop.
go monitor
package main
import (
"encoding/json"
"fmt"
"runtime"
"time"
)
type Monitor struct {
Alloc,
TotalAlloc,
Sys,
Mallocs,
Frees,
LiveObjects,
PauseTotalNs uint64
NumGC uint32
NumGoroutine int
}
func NewMonitor(duration int) {
var m Monitor
var rtm runtime.MemStats
var interval = time.Duration(duration) * time.Second
for {
<-time.After(interval)
// Read full mem stats
runtime.ReadMemStats(&rtm)
// Number of goroutines
m.NumGoroutine = runtime.NumGoroutine()
// Misc memory stats
m.Alloc = rtm.Alloc
m.TotalAlloc = rtm.TotalAlloc
m.Sys = rtm.Sys
m.Mallocs = rtm.Mallocs
m.Frees = rtm.Frees
// Live objects = Mallocs - Frees
m.LiveObjects = m.Mallocs - m.Frees
// GC Stats
m.PauseTotalNs = rtm.PauseTotalNs
m.NumGC = rtm.NumGC
// Just encode to json and print
b, _ := json.Marshal(m)
fmt.Println(string(b))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment