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

关于手动管理内存

  •  
  •   pmispig · Apr 10, 2020 · 2549 views
    This topic created in 2217 days ago, the information mentioned may be changed or developed.

    为了限制程序的总内存大小,所以根据 runtime MemStats 的值来限制用于缓存的结构数组是否允许 append 。 但是带来的问题是在等待 gc 的时间内程序基本处于半睡眠状态,运行效率不高。 所以萌生了想手动管理内存的想法。首先我需要限制单个 struct 的最大内存为 4kb,然后限制[] struct 最大为 1024, 那么可以预先生成一个池

    rows := 1024
    cols := 4096
    pool := make([][]byte, rows)
    for i := 0; i < rows; i++ {
        pool[i] = make([] byte, cols)
    }
    
    

    这样得到一个 byte 池,然后再建立一个状态数组因维护每个坑的使用状态,把 struct 转成[]byte 从 pool 存入 /取出
    你们觉得行不行。。

    9 replies    2020-04-10 22:25:43 +08:00
    xcstream
        1
    xcstream  
       Apr 10, 2020
    可以 但是为什么不用 c 语言呢
    pmispig
        2
    pmispig  
    OP
       Apr 10, 2020
    @xcstream 因为有现成的车,只要从自吸加个电池组变成混动就好了。但是要从头造一个涡轮加速,那工作量就太大了
    pmispig
        3
    pmispig  
    OP
       Apr 10, 2020
    @xcstream 0.0 你是说整个重写用 c 还是分配内存这一块用 c ..
    xcstream
        4
    xcstream  
       Apr 10, 2020
    随便讲讲。

    要关闭 gc 的话环境变量 GOGC=off 就可以了
    cabing
        5
    cabing  
       Apr 10, 2020
    c++或者 rust 走起啊。
    nightwitch
        6
    nightwitch  
       Apr 10, 2020
    用 GC 语言来模拟内存池怪怪的。最好是直接调用 C 语言写的内存池,自己释放和申请内存。
    cmdOptionKana
        7
    cmdOptionKana  
       Apr 10, 2020
    @pmispig 汽油车加个电池组就能变混动???混动的技术难度比纯油或纯电复杂得多好吗。
    Pyjamas
        8
    Pyjamas  
       Apr 10, 2020
    我之前也觉得 GC 语言搞内存池很奇怪,直到前段时间看到 v2ray 里是这么搞的,不过我还没仔细看
    希望这个对你有帮助 https://github.com/v2ray/v2ray-core/blob/master/common/bytespool/pool.go
    NeinChn
        9
    NeinChn  
       Apr 10, 2020
    连 resource pool 的通用的轮子都没有,要自己写 pool 这么惨?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1158 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 23:09 · PVG 07:09 · LAX 16:09 · JFK 19:09
    ♥ Do have faith in what you're doing.