GOGCTRACE and collection time

Go supports the GOGCTRACE environment variable and prints collection statistics every time it starts. However, it does not print when the GC occurred. Example:

gc6231 (8): 0 + 1 + 0 ms, 10 β†’ 5 MB 89540 β†’ 5294 (520316701-520311407) objects, 9 (80) handover, 32 (404) theft, 288/168/37 gives

How can I compare the collection line with the time of its appearance?

+6
source share
1 answer

Tracing does not show the absolute time, but one relative to the output. When the line occurs, GC occurred 0 + 1 + 0 ms ago.

See the corresponding output line in the code for reference.

If you prefix each line to stdout with a timestamp, you get the GC runtime (timestamp - time in milliseconds = time during which GC).

Example:

 GOGCTRACE=1 ./myprog 2>&1 | while read line; do echo $(date +%s) $line; done 

If you just want to feel when the GC crashed in seconds, then that’s enough. The output is likely to keep up with even if it is, you should still have timestamps in order to get the right time.

Another solution would be to use runtime/debug ReadGCStats , which gives you a GCStats structure, which in turn has a LastGC field of type time.Time holding the absolute time of the last GC start. Alternatively, you can use runtime.ReadMemStats , which gives you even more information.

Of course, you still need to know when the garbage collection occurred. To do this, you could use a finalizer on an object that you create solely to be garbage collected and applied by runtime.SetFinalizer . In the finalizer, you then read LastGC time and print it.

Example (on play ):

 type Garbage struct{ a int } func notify(f *Garbage) { stats := &runtime.MemStats{} runtime.ReadMemStats(stats) fmt.Println("Last GC was:", stats.LastGC) go ProduceFinalizedGarbage() } func ProduceFinalizedGarbage() { x := &Garbage{} runtime.SetFinalizer(x, notify) } func main() { go ProduceFinalizedGarbage() for { runtime.GC() time.Sleep(30 * time.Second) // Give GC time to run } } 
+7
source

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


All Articles