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)
source share