Created
August 7, 2018 08:27
-
-
Save changkun/3345491b4dd3919ed802068f9a8ceb3b to your computer and use it in GitHub Desktop.
go monitor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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