V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
pmispig

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

  •  
  •   pmispig · Apr 9, 2020 · 3516 views
    This topic created in 2221 days ago, the information mentioned may be changed or developed.

    由于最近我的 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 replies    2020-04-12 15:38:17 +08:00
    heimeil
        1
    heimeil  
       Apr 9, 2020
    https://pkg.go.dev/runtime?tab=doc#ReadMemStats
    直接定时获取一下已申请内存大小
    pmispig
        2
    pmispig  
    OP
       Apr 9, 2020
    @heimeil 这个好像不错,先安排上,多谢
    snowfuck
        3
    snowfuck  
       Apr 9, 2020
    这是 go 的内存布局相关的内容,我之前也查过一些资料,可以看这里: https://www.flysnow.org/2017/07/02/go-in-action-unsafe-memory-layout.html
    结合 google 还有更多资料。
    ProbeWong
        4
    ProbeWong  
       Apr 9, 2020 via Android
    B 站 go 夜读 是说 go 源码的,最近的一期就是聊这个内存对齐 可以参考下
    secondwtq
        5
    secondwtq  
       Apr 10, 2020
    野蛮路子:运行时创建 1G 个该类型的值,观察内存占用

    这方法我还真用过两次,拿来猜闭源软件里的一些功能是如何实现的
    aliipay
        6
    aliipay  
       Apr 12, 2020
    只是为了避免 out of memory,可以考虑直接获取进程的 rss 值
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1062 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 56ms · UTC 18:35 · PVG 02:35 · LAX 11:35 · JFK 14:35
    ♥ Do have faith in what you're doing.