gin/examples/realtime-advanced/stats.go

60 lines
1.2 KiB
Go
Raw Normal View History

2015-05-13 00:35:16 +00:00
package main
import (
"runtime"
2015-05-13 18:54:54 +00:00
"sync"
2015-05-13 00:35:16 +00:00
"time"
2015-05-14 16:16:00 +00:00
"github.com/manucorporat/stats"
2015-05-13 00:35:16 +00:00
)
2017-06-15 02:14:25 +00:00
var (
ips = stats.New()
messages = stats.New()
users = stats.New()
mutexStats sync.RWMutex
savedStats map[string]uint64
)
2015-05-13 18:54:54 +00:00
func statsWorker() {
c := time.Tick(1 * time.Second)
2016-04-14 23:16:46 +00:00
var lastMallocs uint64
var lastFrees uint64
for range c {
2015-05-13 18:54:54 +00:00
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
2015-05-13 00:35:16 +00:00
2015-05-13 18:54:54 +00:00
mutexStats.Lock()
savedStats = map[string]uint64{
2015-05-14 16:16:00 +00:00
"timestamp": uint64(time.Now().Unix()),
"HeapInuse": stats.HeapInuse,
"StackInuse": stats.StackInuse,
"Mallocs": stats.Mallocs - lastMallocs,
"Frees": stats.Frees - lastFrees,
2015-05-14 16:16:00 +00:00
"Inbound": uint64(messages.Get("inbound")),
"Outbound": uint64(messages.Get("outbound")),
"Connected": connectedUsers(),
2015-05-13 18:54:54 +00:00
}
2015-05-14 16:16:00 +00:00
lastMallocs = stats.Mallocs
lastFrees = stats.Frees
2015-05-14 15:01:02 +00:00
messages.Reset()
2015-05-13 18:54:54 +00:00
mutexStats.Unlock()
2015-05-13 00:35:16 +00:00
}
}
2015-05-13 18:54:54 +00:00
2015-05-14 16:16:00 +00:00
func connectedUsers() uint64 {
connected := users.Get("connected") - users.Get("disconnected")
if connected < 0 {
return 0
}
return uint64(connected)
}
// Stats returns savedStats data.
2015-05-13 18:54:54 +00:00
func Stats() map[string]uint64 {
mutexStats.RLock()
defer mutexStats.RUnlock()
return savedStats
}