How to track memory usage?

I am trying to create a small tool that will allow me to run a program and track memory usage through Go. I use r.exec = exec.Command(r.Command, r.CommandArgs...)runtime.MemStats to run the memory usage tracking command (in a separate go procedure):

func monitorRuntime() {
    m := &runtime.MemStats{}
    f, err := os.Create(fmt.Sprintf("mmem_%s.csv", getFileTimeStamp()))
    if err != nil {
        panic(err)
    }
    f.WriteString("Time;Allocated;Total Allocated; System Memory;Num Gc;Heap Allocated;Heap System;Heap Objects;Heap Released;\n")
    for {
        runtime.ReadMemStats(m)
        f.WriteString(fmt.Sprintf("%s;%d;%d;%d;%d;%d;%d;%d;%d;\n", getTimeStamp(), m.Alloc, m.TotalAlloc, m.Sys, m.NumGC, m.HeapAlloc, m.HeapSys, m.HeapObjects, m.HeapReleased))
        time.Sleep(5 * time.Second)
    }
}

When I checked my code with a simple program that just sits there (about 12 hours), I noticed that Go constantly allocates more memory: System memory Heap allocation

I did some more tests, such as running a function monitorRuntime()without any other code or using pprof, for example:

package main

import (
    "net/http"
    _ "net/http/pprof"
)

func main() {
    http.ListenAndServe(":8080", nil)
}

But I still noticed that the memory allocation continues to grow, as in the graphs.

, ? , , - /proc/$PID/statm, (, Mac OS Windows).

+4

Source: https://habr.com/ru/post/1668423/


All Articles