写了一个从视频中截取预览图的工具,
使用 go 1.7
用这个库:
github.com/opennota/screengen
测试时发现内存一直涨,根本就停不下来,最后能服机器搞死,而且无论等多久内存占用也不会降下来
开始以为是第三方库的问题,最后测试发现了点不一样的东西,
具体如下:
```
top
(pprof) top
18412.15MB of 18506.45MB total (99.49%)
Dropped 21 nodes (cum <= 92.53MB)
flat flat% sum% cum cum%
18411.15MB 99.49% 99.49% 18411.65MB 99.49% github.com/opennota/screengen.(*Generator).ImageWxH
1MB 0.0054% 99.49% 18505.45MB 100% main.(*Thumbsrv).thumbtt
0 0% 99.49% 18411.65MB 99.49% github.com/opennota/screengen.(*Generator).Image
0 0% 99.49% 18505.45MB 100% main.main
0 0% 99.49% 18505.45MB 100% main.testrun
0 0% 99.49% 18505.95MB 100% runtime.goexit
0 0% 99.49% 18505.95MB 100% runtime.main
(pprof)
```
细节:
```
17.98GB 17.98GB (flat, cum) 99.49% of Total
. . 196: }
. . 197: }
. . 198:
. . 199: rec := image.Rect(0, 0, width, height)
. . 200:
17.96GB 17.96GB 201: img := image.NewRGBA(rec)
. . 202:
. . 203:
. . 204: //w, h := imm.Dx(), imm.Dy()
. . 205: //buf := make([]uint8, 4*w*h)
. . 206: //img := &image.RGBA{buf, 4 * w, imm}
. . 207:
. . 208: frame := C.av_frame_alloc()
. . 209: defer C.av_frame_free(&frame)
. . 210: C.avcodec_flush_buffers(g.avcContext)
1.50MB 1.50MB 211: var pkt C.struct_AVPacket
```
原因是这个地方:
```
img := image.NewRGBA(rec)
```
但最根本原因是NewRGBA方法里的这个地方:
```
buf := make([]uint8, 4*w*h)
```
这可是标准库里的呀,
那么问题来了,
该怎么解决此问题?
有疑问加站长微信联系(非本文作者)