Golang中的CPU占满100%及解决方案

 

CPUCPUbug
发现CPU开销很大
CPU
Time: Mar 22, 2019 at 5:52pm (CST)
Duration: 1mins, Total samples = 1.43mins (142.57%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) tree 
Showing nodes accounting for 83.13s, 97.11% of 85.60s total
Dropped 256 nodes (cum <= 0.43s)
----------------------------------------------------------+-------------
      flat  flat%   sum%        cum   cum%   calls calls% + context           
----------------------------------------------------------+-------------
                                            71.36s 99.86% |   runtime.gcDrain
                                             0.10s  0.14% |   runtime.systemstack
    48.56s 56.73% 56.73%     71.46s 83.48%                | runtime.scanobject
                                            11.86s 16.60% |   runtime.heapBitsForObject
                                            11.04s 15.45% |   runtime.greyobject
----------------------------------------------------------+-------------
                                            11.86s 99.92% |   runtime.scanobject
    11.87s 13.87% 70.60%     11.87s 13.87%                | runtime.heapBitsForObject
----------------------------------------------------------+-------------
                                            11.04s   100% |   runtime.scanobject
    11.02s 12.87% 83.47%     11.04s 12.90%                | runtime.greyobject
----------------------------------------------------------+-------------
                                             6.53s 95.05% |   runtime.gosweepone.func1
                                             0.34s  4.95% |   runtime.(*mheap).alloc
     4.34s  5.07% 88.54%      6.87s  8.03%                | runtime.sweepone
                                             2.53s 36.83% |   runtime.(*mspan).sweep
----------------------------------------------------------+-------------
                                            74.42s   100% |   runtime.gcBgMarkWorker.func2
     1.97s  2.30% 90.84%     74.42s 86.94%                | runtime.gcDrain
                                            71.36s 95.89% |   runtime.scanobject
                                             0.52s   0.7% |   runtime.pollWork
----------------------------------------------------------+-------------
准备工作
buffer pool
    // 这里不再分配新的内存,而是从 buffer pool 里面 GET 
    databuf = make([]byte, 100000)
解决
buffer poolGetPutGetPut
是什么原因导致了CPU开销很大(重点)
byte

memory.png

Golang
GolangCPUCPU

解决办法

buffer pool
buffer poolbuffer poolGetPut

bufferpool.png

buffer poolCPU

打个比方

比如说操作系统就是一个土豪,借东西再换回来不收利息。它有一个很大的内存,周围许多人都想找它去借(新声明的变量并初始化),刚开始借的人只有十几个,后面有上万个,于是它要每天记录谁借了多少内存出去,谁还没有归还,归还的直接从记录上把名字划掉(垃圾回收)。后来操作系统烦了,于是就建了一个很大的内存池,够所有人分批次借,只要借完及时归还就行,而它每次去看这个内存池有没有变小即可,省了不少精力。

go buffer pool

注意

GetPutCPUGolang
参考文章和资源