栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

进行内存消耗管理

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

进行内存消耗管理

当前,go使用标记清除垃圾收集器,该收集器通常不定义何时丢弃对象。

但是,如果仔细观察,就会有一个go例程被调用

sysmon
,该例程实际上只要您的程序运行就运行,并定期调用GC:

// forcegcperiod is the maximum time in nanoseconds between garbage// collections. If we go this long without a garbage collection, one// is forced to run.//// This is a variable for testing purposes. It normally doesn't change.var forcegcperiod int64 = 2 * 60 * 1e9(...)// If a heap span goes unused for 5 minutes after a garbage collection,// we hand it back to the operating system.scavengelimit := int64(5 * 60 * 1e9)

forcegcperiod
确定强制调用GC的时间段。
scavengelimit
确定何时将跨度返回到操作系统。跨度是可以容纳多个对象的许多内存页面。它们会保留
scavengelimit
一段时间,如果它们上没有对象且
scavengelimit
超出了限制,它们将被释放。

在代码的更下方,您可以看到有一个跟踪选项。每当拾荒者认为他需要清理时,您可以使用它来查看:

$ GOGCTRACE=1 go run gc.gogc1(1): 0+0+0 ms 0 -> 0 MB 423 -> 350 (424-74) objects 0 handoffgc2(1): 0+0+0 ms 1 -> 0 MB 2664 -> 1437 (2880-1443) objects 0 handoffgc3(1): 0+0+0 ms 1 -> 0 MB 4117 -> 2213 (5712-3499) objects 0 handoffgc4(1): 0+0+0 ms 2 -> 1 MB 3128 -> 2257 (6761-4504) objects 0 handoffgc5(1): 0+0+0 ms 2 -> 0 MB 8892 -> 2531 (13734-11203) objects 0 handoffgc6(1): 0+0+0 ms 1 -> 1 MB 8715 -> 2689 (20173-17484) objects 0 handoffgc7(1): 0+0+0 ms 2 -> 1 MB 5231 -> 2406 (22878-20472) objects 0 handoffgc1(1): 0+0+0 ms 0 -> 0 MB 172 -> 137 (173-36) objects 0 handoffgetting memorygc2(1): 0+0+0 ms 381 -> 381 MB 203 -> 202 (248-46) objects 0 handoffreturning memorygetting memoryreturning memory

如您所见,在获取和返回之间没有gc调用完成。但是,如果您将延迟时间从5秒更改为3分钟(大于的2分钟

forcegcperiod
),则对象会被gc删除:

returning memoryscvg0: inuse: 1, idle: 1, sys: 3, released: 0, consumed: 3 (MB)scvg0: inuse: 381, idle: 0, sys: 382, released: 0, consumed: 382 (MB)scvg1: inuse: 1, idle: 1, sys: 3, released: 0, consumed: 3 (MB)scvg1: inuse: 381, idle: 0, sys: 382, released: 0, consumed: 382 (MB)gc9(1): 1+0+0 ms 1 -> 1 MB 4485 -> 2562 (26531-23969) objects 0 handoffgc10(1): 1+0+0 ms 1 -> 1 MB 2563 -> 2561 (26532-23971) objects 0 handoffscvg2: GC forced // forcegc (2 minutes) exceededscvg2: inuse: 1, idle: 1, sys: 3, released: 0, consumed: 3 (MB)gc3(1): 0+0+0 ms 381 -> 381 MB 206 -> 206 (252-46) objects 0 handoffscvg2: GC forcedscvg2: inuse: 381, idle: 0, sys: 382, released: 0, consumed: 382 (MB)getting memory

仍然没有释放内存,但是GC将内存区域标记为未使用。当使用的跨度未使用且早于时,将开始释放

limit
。从清除代码:

if(s->unusedsince != 0 && (now - s->unusedsince) > limit) {    // ...    runtime·SysUnused((void*)(s->start << PageShift), s->npages << PageShift);}

这种行为当然会随着时间的流逝而改变,但是我希望当物体被强行扔掉时和不被抛弃时,您现在能有所体会。

正如zupa指出的那样,释放对象可能不会将内存返回给操作系统,因此在某些系统上,您可能看不到内存使用情况的变化。根据golang-
nuts上的该线程,
对于Plan 9和Windows似乎是这种情况。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/568923.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号