Skip to content

Instantly share code, notes, and snippets.

@mdouchement
Last active June 3, 2016 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdouchement/b6372bce4d10f45cf8821bbde7562560 to your computer and use it in GitHub Desktop.
Save mdouchement/b6372bce4d10f45cf8821bbde7562560 to your computer and use it in GitHub Desktop.
Golang memory profiler
package profiler
import (
"github.com/wblakecaldwell/profiler"
"net/http"
"sync"
)
var cache = struct {
sync.RWMutex
mapping map[string]interface{}
}{
mapping: make(map[string]interface{}),
}
func Run() {
profiler.AddMemoryProfilingHandlers()
profiler.RegisterExtraServiceInfoRetriever(mapping)
profiler.StartProfiling()
println("Profiler started on http://localhot:6060/profiler/info.html")
http.ListenAndServe(":6060", nil)
}
func UpdateMapping(key string, value interface{}) {
cache.Lock()
cache.mapping[key] = value
cache.Unlock()
}
func mapping() map[string]interface{} {
cache.RLock()
defer cache.RUnlock()
copy := map[string]interface{}{}
for k, v := range cache.mapping {
copy[k] = v
}
return copy
}
func String(key string) string {
if value, ok := mapping()[key].(string); ok {
return value
}
return ""
}
func Bool(key string) bool {
if value, ok := mapping()[key].(bool); ok {
return value
}
return false
}
func Int(key string) int {
if value, ok := mapping()[key].(int); ok {
return value
}
return 0
}
func Float64(key string) float64 {
if value, ok := mapping()[key].(float64); ok {
return value
}
return 0.0
}
func Uint64(key string) uint64 {
if value, ok := mapping()[key].(uint64); ok {
return value
}
return 0
}
package main
// import profiler
func main() {
go profiler.Run()
var i uint64
for {
profiler.UpdateMapping("iterations", i)
profiler.UpdateMapping("iterations cached only", profiler.Uint64("iterations cached only")+1)
i++
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment