-
-
Save whyrusleeping/b0431561b23a5c1d8b2dfce5526751aa to your computer and use it in GitHub Desktop.
a thing to watch memory usage
This file contains 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 ( | |
"fmt" | |
"os" | |
"runtime" | |
"runtime/pprof" | |
"time" | |
) | |
func Watch(threshold uint64, maxFreq time.Duration, cb func()) { | |
var lastNotif time.Time | |
for range time.Tick(time.Second) { | |
var mstats runtime.MemStats | |
runtime.ReadMemStats(&mstats) | |
if mstats.Alloc > threshold && time.Since(lastNotif) > maxFreq { | |
cb() | |
lastNotif = time.Now() | |
} | |
} | |
} | |
func main() { | |
go Watch(1<<30, time.Second*60*5, func() { | |
fmt.Println("memory threshold triggered! writing profile!") | |
fi, err := os.Create(fmt.Sprintf("high-mem-profile-%d", time.Now().UnixNano())) | |
if err != nil { | |
fmt.Println("Error: failed to open file for memory profile: ", err) | |
return | |
} | |
defer fi.Close() | |
if err := pprof.WriteHeapProfile(fi); err != nil { | |
fmt.Println("failed to write memory profile: ", err) | |
} | |
}) | |
var stuff [][]byte | |
for range time.Tick(time.Millisecond) { | |
stuff = append(stuff, make([]byte, 500000)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment