duanbichou4942 2013-11-15 11:48
浏览 18

根据内存消耗自动清除缓存

I want to implement an efficient LRU cache that automatically evicts items based on free memory.

Right now only 2 things come to mind:

  • Poll with gosigar
  • or set a fixed maximum and periodically check runtime.ReadMemStats.

Are there any other ways? How does memcached do it?

  • 写回答

1条回答 默认 最新

  • duandeng2265 2013-11-16 20:28
    关注

    I implemented it polling the system memory statistics every 1 second.

    See: https://github.com/eaigner/last

    Read memory stats on Linux:

    import (
        "syscall"
    )
    
    func ReadSysMemStats(s *MemStats) error {
        if s == nil {
            return nil
        }
        var info syscall.Sysinfo_t
        err := syscall.Sysinfo(&info)
        if err != nil {
            return err
        }
    
        s.Total = info.Totalram
        s.Free = info.Freeram
        s.Used = s.Total - s.Free
    
        return nil
    }
    

    And on Darwin/OSX

    /*
    #include <mach/mach.h>
    #include <mach/mach_host.h>
    */
    import "C"
    
    import (
        "fmt"
        "unsafe"
    )
    
    func readSysMemStats(s *SysMemStats) error {
        if s == nil {
            return nil
        }
        var vm_pagesize C.vm_size_t
        var vm_stat C.vm_statistics_data_t
        var count C.mach_msg_type_number_t = C.HOST_VM_INFO_COUNT
    
        host_port := C.host_t(C.mach_host_self())
    
        C.host_page_size(host_port, &vm_pagesize)
    
        status := C.host_statistics(
            host_port,
            C.HOST_VM_INFO,
            C.host_info_t(unsafe.Pointer(&vm_stat)),
            &count)
    
        if status != C.KERN_SUCCESS {
            return fmt.Errorf("could not get vm statistics: %d", status)
        }
    
        // Stats in bytes
        free := uint64(vm_stat.free_count)
        active := uint64(vm_stat.active_count)
        inactive := uint64(vm_stat.inactive_count)
        wired := uint64(vm_stat.wire_count)
        pagesize := uint64(vm_pagesize)
    
        s.Used = (active + inactive + wired) * pagesize
        s.Free = free * pagesize
        s.Total = s.Used + s.Free
    
        return nil
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)