1. Memory Alignment
Arrange the fields inside a struct from largest to smallest.
This reduces memory footprint.
- Install the fieldalignment tool
| |
- Analyze and fix memory alignment
| |
- Look at the optimizations fieldalignment performs
Before optimization, struct of size 96
| |
After optimization, struct of size 88
| |
fieldalignment automatically sorts the fields in a struct, from largest to smallest.
The reason is that during compilation the Go compiler, for the sake of CPU access efficiency, applies a certain memory alignment strategy to ensure that a complete field can be read in as close to a single atomic read as possible. But this strategy leaves holes in structs in memory, which increases memory usage.
2. Setting a Reasonable GOMAXPROCS
Write a program that gets the current CPU core count and shows the current GOMAXPROCS value.
| |
Pod Request CPU is 10, Limit CPU is 20.
| |
The value of GOMAXPROCS is the CPU core count of the physical machine, not the container’s CPU core count. An excessively large GOMAXPROCS leads to severe context switching and wasted CPU. In a container environment, a Go program cannot set GOMAXPROCS optimally on its own; you need to set it based on the container’s CPU core count.
- The first way is to set the GOMAXPROCS environment variable, which specifies the maximum number of Ps
| |
| |
The program automatically reads the value of GOMAXPROCS from the environment variable and applies it.
- The second way is to use the automaxprocs package to set GOMAXPROCS automatically.
| |
After the package is imported, the init method runs automatically, gets the Pod’s CPU Limit value, and sets GOMAXPROCS.
| |
If you use both at once, the environment variable takes priority over the automaxprocs package.
| |
| |
