3 min read | by Jordi Prats
Go is a garbage-collected language: It will reclaim any unused memory. This automation can sometimes introduce performance challenges. We can use the GODEBUG environment variable to provide insights into specific internal operations of the Go runtime, such as scheduling, memory allocation, and garbage collection.
We can set the GODEBUG
environment variable to gctrace=1
to enable tracing for the garbage collector. Go is going to output detailed logs about each garbage collection cycle to the standard error output. This is particularly useful for understanding how often garbage collection is happening, how much time it is taking, and how it affects the overall performance of your application.
gc 1 @0.005s 0%: 0.006+0.29+0.003 ms clock, 0.068+0.043/0.47/0.057+0.034 ms cpu, 3->3->0 MB, 4 MB goal, 0 MB stacks, 0 MB globals, 10 P
gc 2 @0.010s 1%: 0.025+0.29+0.004 ms clock, 0.25+0.21/0.52/0.006+0.045 ms cpu, 3->3->1 MB, 4 MB goal, 0 MB stacks, 0 MB globals, 10 P
(...)
gc 1 @0.007s 4%: 0.022+0.53+0.17 ms clock, 0.22+0.17/1.1/0.25+1.7 ms cpu, 3->4->2 MB, 4 MB goal, 0 MB stacks, 0 MB globals, 10 P
gc 47 @128.598s 0%: 0.21+4.4+0.004 ms clock, 2.1+0/13/0+0.047 ms cpu, 50->50->16 MB, 62 MB goal, 0 MB stacks, 0 MB globals, 10 P
GC forced
In the previous example, the lines starting with gc
are telling us the following information (using the first line as an example):
gc
, indicating that this is a garbage collection cycle.gc
is the garbage collection number. This is a counter that increments with each garbage collection cycle. If we see it going back to 1, it's just another child reporting it's stats.We might also see some lines with GC forced
. This means that the garbage collector was forced to run even though it wasn't necessary: It will forcefully run every two minutes, being just an heuristic to keep the memory usage under control.
To learn more about the garbage collector in Go, you can check the official documentation at https://tip.golang.org/doc/gc-guide.
Posted on 30/10/2024