V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
pmispig
V2EX  ›  Go 编程语言

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

  •  
  •   pmispig · 2020-04-09 15:01:32 +08:00 · 2854 次点击
    这是一个创建于 1471 天前的主题,其中的信息可能已经有所发展或是发生改变。

    由于最近我的 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 有很多问题,还说这个只是在编译时计算。 不优雅也行,野蛮点也可以。。。

    6 条回复    2020-04-12 15:38:17 +08:00
    heimeil
        1
    heimeil  
       2020-04-09 15:30:52 +08:00
    https://pkg.go.dev/runtime?tab=doc#ReadMemStats
    直接定时获取一下已申请内存大小
    pmispig
        2
    pmispig  
    OP
       2020-04-09 15:33:55 +08:00
    @heimeil 这个好像不错,先安排上,多谢
    snowfuck
        3
    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
        4
    ProbeWong  
       2020-04-09 15:52:04 +08:00 via Android
    B 站 go 夜读 是说 go 源码的,最近的一期就是聊这个内存对齐 可以参考下
    secondwtq
        5
    secondwtq  
       2020-04-10 01:07:23 +08:00
    野蛮路子:运行时创建 1G 个该类型的值,观察内存占用

    这方法我还真用过两次,拿来猜闭源软件里的一些功能是如何实现的
    aliipay
        6
    aliipay  
       2020-04-12 15:38:17 +08:00
    只是为了避免 out of memory,可以考虑直接获取进程的 rss 值
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   918 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 20:39 · PVG 04:39 · LAX 13:39 · JFK 16:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.