golang 中怎么优雅地计算结构占用的内存大小

2020-04-09 15:01:32 +08:00
 pmispig

由于最近我的 filebeat 频繁地 out of memory 。filebeat 只能限制 queue 条数,而不能限制 cache 内存大小,准备小小改造一下

type common.MapStr map[string]interface{}

type EventCache struct {
	m common.MapStr
}

type EventFlags uint8

type beat.Event struct {
	Timestamp  time.Time
	Meta       common.MapStr
	Fields     common.MapStr
	Private    interface{} // for beats private use
	TimeSeries bool        // true if the event contains timeseries data
}

type Event struct {
	Content beat.Event
	Flags   EventFlags
	Cache   EventCache
}

想请问下怎么在运行时优雅地计算 Event 这个结构所占用的内存大小,看到说 unsafe.sizeof 有很多问题,还说这个只是在编译时计算。 不优雅也行,野蛮点也可以。。。

2898 次点击
所在节点    Go 编程语言
6 条回复
heimeil
2020-04-09 15:30:52 +08:00
https://pkg.go.dev/runtime?tab=doc#ReadMemStats
直接定时获取一下已申请内存大小
pmispig
2020-04-09 15:33:55 +08:00
@heimeil 这个好像不错,先安排上,多谢
snowfuck
2020-04-09 15:38:53 +08:00
这是 go 的内存布局相关的内容,我之前也查过一些资料,可以看这里: https://www.flysnow.org/2017/07/02/go-in-action-unsafe-memory-layout.html
结合 google 还有更多资料。
ProbeWong
2020-04-09 15:52:04 +08:00
B 站 go 夜读 是说 go 源码的,最近的一期就是聊这个内存对齐 可以参考下
secondwtq
2020-04-10 01:07:23 +08:00
野蛮路子:运行时创建 1G 个该类型的值,观察内存占用

这方法我还真用过两次,拿来猜闭源软件里的一些功能是如何实现的
aliipay
2020-04-12 15:38:17 +08:00
只是为了避免 out of memory,可以考虑直接获取进程的 rss 值

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/660807

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX