• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang mem.VirtualMemory函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/shirou/gopsutil/mem.VirtualMemory函数的典型用法代码示例。如果您正苦于以下问题:Golang VirtualMemory函数的具体用法?Golang VirtualMemory怎么用?Golang VirtualMemory使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了VirtualMemory函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: GetNodeResource

/**
	read node resource usage
**/
func GetNodeResource(w http.ResponseWriter, r *http.Request) {
	// get this node memory
	memory, _ := mem.VirtualMemory()
	// get this node cpu percent usage
	cpu_percent, _ := cpu.CPUPercent(time.Duration(1)*time.Second, false)
	// Disk mount Point
	disk_partitions, _ := disk.DiskPartitions(true)
	// Disk usage
	var disk_usages []*disk.DiskUsageStat
	for _, disk_partition := range disk_partitions {
		if disk_partition.Mountpoint == "/" || disk_partition.Mountpoint == "/home" {
			disk_stat, _ := disk.DiskUsage(disk_partition.Device)
			disk_usages = append(disk_usages, disk_stat)
		}
	}
	// Network
	network, _ := net.NetIOCounters(false)

	// create new node obj with resource usage information
	node_metric := thoth.NodeMetric{
		Cpu:       cpu_percent,
		Memory:    memory,
		DiskUsage: disk_usages,
		Network:   network,
	}

	node_json, err := json.MarshalIndent(node_metric, "", "\t")
	if err != nil {
		fmt.Println("error:", err)
	}
	fmt.Fprint(w, string(node_json))
}
开发者ID:SOUP-CE-KMITL,项目名称:Thoth,代码行数:35,代码来源:handler.go


示例2: MemoryUsage

// MemoryUsage - XXX
func MemoryUsage() MemoryStruct {
	mem, _ := psmem.VirtualMemory()
	swap, _ := psmem.SwapMemory()

	TotalMB, _ := util.ConvertBytesTo(mem.Total, "mb", 0)
	FreeMB, _ := util.ConvertBytesTo(mem.Free, "mb", 0)
	UsedMB, _ := util.ConvertBytesTo(mem.Used, "mb", 0)
	UsedPercent, _ := util.FloatDecimalPoint(mem.UsedPercent, 0)
	SwapUsedMB, _ := util.ConvertBytesTo(swap.Used, "mb", 0)
	SwapTotalMB, _ := util.ConvertBytesTo(swap.Total, "mb", 0)
	SwapFreeMB, _ := util.ConvertBytesTo(swap.Free, "mb", 0)
	SwapUsedPercent, _ := util.FloatDecimalPoint(swap.UsedPercent, 0)

	m := MemoryStruct{
		UsedMB:          UsedMB,
		TotalMB:         TotalMB,
		FreeMB:          FreeMB,
		UsedPercent:     UsedPercent,
		SwapUsedMB:      SwapUsedMB,
		SwapTotalMB:     SwapTotalMB,
		SwapFreeMB:      SwapFreeMB,
		SwapUsedPercent: SwapUsedPercent,
	}

	return m
}
开发者ID:amonapp,项目名称:amonagent,代码行数:27,代码来源:memory.go


示例3: GetSystem

// GetSystem gets statistics about the system
func GetSystem() *api.SystemStats {
	status := new(api.SystemStats)
	if load, err := load.Avg(); err == nil {
		status.Load = &api.SystemStats_Loadstats{
			Load1:  float32(load.Load1),
			Load5:  float32(load.Load5),
			Load15: float32(load.Load15),
		}
	}
	if cpu, err := cpu.Times(false); err == nil && len(cpu) == 1 {
		status.Cpu = &api.SystemStats_CPUStats{
			User:   float32(cpu[0].User),
			System: float32(cpu[0].System),
			Idle:   float32(cpu[0].Idle),
		}
	}
	if mem, err := mem.VirtualMemory(); err == nil {
		status.Memory = &api.SystemStats_MemoryStats{
			Total:     mem.Total,
			Available: mem.Available,
			Used:      mem.Used,
		}
	}
	return status
}
开发者ID:TheThingsNetwork,项目名称:ttn,代码行数:26,代码来源:stats.go


示例4: MemInfo

func MemInfo() (*Mem, error) {
	info, err := mem.VirtualMemory()
	if err != nil {
		return nil, err
	}
	return &Mem{info.Buffers, info.Cached, info.Total, info.Available, 0, 0, 0}, nil
}
开发者ID:shenjh369,项目名称:nux,代码行数:7,代码来源:meminfo_windows.go


示例5: Generate

func (m Memory) Generate() ([]i3.Output, error) {
	mem, err := mem.VirtualMemory()
	if err != nil {
		return nil, err
	}

	total := mem.Total
	used := total - mem.Buffers - mem.Cached - mem.Free

	percUsed := (100 * used) / total

	var color string
	switch {
	case m.IsCrit(int(percUsed)):
		color = i3.DefaultColors.Crit
	case m.IsWarn(int(percUsed)):
		color = i3.DefaultColors.Warn
	default:
		color = i3.DefaultColors.OK
	}

	out := make([]i3.Output, 1)
	out[0] = i3.Output{
		Name:      m.Name,
		FullText:  fmt.Sprintf(FormatString, percUsed, bytefmt.ByteSize(used), bytefmt.ByteSize(total)),
		Color:     color,
		Separator: true,
	}

	return out, nil
}
开发者ID:codekoala,项目名称:goi3bar,代码行数:31,代码来源:mem.go


示例6: GetHardwareProfile

func GetHardwareProfile() (*pb.HardwareProfile, error) {
	v, err := mem.VirtualMemory()
	if err != nil {
		return &pb.HardwareProfile{}, err
	}
	d, err := disk.Partitions(true)
	if err != nil {
		return &pb.HardwareProfile{}, err
	}
	hw := &pb.HardwareProfile{
		Disks:    make([]*pb.Disk, 0),
		Cpus:     int64(runtime.NumCPU()),
		Memtotal: v.Total,
		Memfree:  v.Free,
	}
	for k := range d {
		usage, err := disk.Usage(d[k].Mountpoint)
		if err != nil {
			continue
		}
		entry := &pb.Disk{
			Path:   d[k].Mountpoint,
			Device: d[k].Device,
			Size_:  usage.Total,
			Used:   usage.Used,
		}
		hw.Disks = append(hw.Disks, entry)
	}
	return hw, nil
}
开发者ID:getcfs,项目名称:cfs-binary-release,代码行数:30,代码来源:srvconf.go


示例7: main

func main() {
	cloud, err := cloud.NewDbusForComDevicehiveCloud()
	if err != nil {
		log.Panic(err)
	}

	h, _ := os.Hostname()

	for {
		time.Sleep(time.Second)
		c, err := cpu.CPUPercent(time.Second, false)
		if err != nil {
			log.Panic(err)
		}

		v, err := mem.VirtualMemory()
		if err != nil {
			log.Panic(err)
		}

		if len(c) > 0 {
			cloud.SendNotification("stats", map[string]interface{}{
				"cpu-usage":    c[0],
				"memory-total": v.Total,
				"memory-free":  v.Free,
				"name":         h,
			}, 1)
		}
	}
}
开发者ID:ndjido,项目名称:IoT-framework,代码行数:30,代码来源:cpu-stats.go


示例8: StartMonitorTask

func StartMonitorTask(dir string, filename string) {

	mylog.GetMonitorLogger().Init(dir, filename)

	mylog.GetMonitorLogger().Write("Time  UsedPercent HeapAlloc HeapObjects Alloc NumGC  NumGor\n")
	// alloc, frees
	// 内存

	for {
		logBuffer := new(bytes.Buffer)

		var runMem runtime.MemStats
		runtime.ReadMemStats(&runMem)
		memStat, _ := mem.VirtualMemory()

		fmt.Fprintf(logBuffer, "%v %v %v %v %v %v\n",
			memStat.UsedPercent,
			runMem.HeapAlloc/(M1),
			runMem.HeapObjects,
			runMem.Alloc/(M1),
			runMem.NumGC,
			runtime.NumGoroutine())

		mylog.GetMonitorLogger().Write(logBuffer.String())
		time.Sleep(10 * time.Second)

	}

}
开发者ID:youxidev,项目名称:HLSWebServer,代码行数:29,代码来源:statist.go


示例9: ExpireBlockStep

//指定时间内扫描cache
func (c *Cache) ExpireBlockStep() int64 {
	c.Lock()
	defer c.Unlock()

	m, err := mem.VirtualMemory()
	if err != nil {
		return int64(0)
	}
	//小于最小触发值,return
	if m.UsedPercent <= c.MinMemUsage {
		return int64(0)
	}
	for file, b := range c.Blocks {
		internal := time.Now().Sub(time.Unix(b.LastAccess, 0))
		if internal >= c.Expire {
			c.ctx.s.logf("expire file: %s, %#v", file, b)
			delete(c.Blocks, file)
			return int64(1)
		}
		if m.UsedPercent >= c.MaxMemUsage {
			if b.lastFiveIdx != 0 && b.lastFiveAccess[b.lastFiveIdx]-b.lastFiveAccess[0] >= 10 {
				c.ctx.s.logf("expire file: %s, %#v", file, b)
				delete(c.Blocks, file)
				return int64(1)
			}
		}
	}
	return int64(0)
}
开发者ID:jash16,项目名称:download,代码行数:30,代码来源:cache.go


示例10: main

func main() {
	v, _ := mem.VirtualMemory()

	// almost every return value is a struct
	fmt.Printf("Total: %v, Free:%v, UsedPercent:%f%%\n", v.Total, v.Free, v.UsedPercent)

	// convert to JSON. String() is also implemented
	fmt.Println(v)

	h, err := host.HostInfo()
	if err != nil {
		fmt.Println("err:", err)
	} else {

		fmt.Printf("hostname %v", h)
	}

	c, err := cpu.CPUInfo()
	if err != nil {
		fmt.Println("err:", err)
	}
	for _, v := range c {
		fmt.Printf("cpu info %v \n ", v)
	}

}
开发者ID:ohlinux,项目名称:golang-snippet-cn,代码行数:26,代码来源:gopsutil-serverinfo.go


示例11: updateMemory

func updateMemory() {
	v, err = mem.VirtualMemory()
	log.Printf("updateMemory(): %v", spew.Sdump(v))
	if err != nil {
		log.Fatal(err)
	}
}
开发者ID:ashmckenzie,项目名称:sysdeets,代码行数:7,代码来源:main.go


示例12: gaugesUpdate

func gaugesUpdate(results runner.BenchmarkResults) {
	if s, err := load.Avg(); err == nil {
		gauges["cpu_load1"].Set(s.Load1)
		gauges["cpu_load5"].Set(s.Load5)
		gauges["cpu_load15"].Set(s.Load15)
	}
	if s, err := mem.VirtualMemory(); err == nil {
		gauges["mem_total"].Set(float64(s.Total))
		gauges["mem_used"].Set(float64(s.Used))
	}
	if s, err := disk.Usage("/"); err == nil {
		gauges["disk_total"].Set(float64(s.Total))
		gauges["disk_used"].Set(float64(s.Used))
	}

	if results != nil {
		gauges["io_time"].Set(results["IO"].Time)
		gauges["io_wall_time"].Set(results["IO"].WallTime)
		gauges["io_memory"].Set(float64(results["IO"].Memory))
		gauges["cpu_time"].Set(results["CPU"].Time)
		gauges["cpu_wall_time"].Set(results["CPU"].WallTime)
		gauges["cpu_memory"].Set(float64(results["CPU"].Memory))
		gauges["memory_time"].Set(results["Memory"].Time)
		gauges["memory_wall_time"].Set(results["Memory"].WallTime)
		gauges["memory_memory"].Set(float64(results["Memory"].Memory))
	}
}
开发者ID:lhchavez,项目名称:quark,代码行数:27,代码来源:metrics.go


示例13: memory

func memory() string {
	v, err := mem.VirtualMemory()
	if err != nil {
		log.Println(err)
	}
	return fmt.Sprintf("%3d%%", int(v.UsedPercent))
}
开发者ID:Duncaen,项目名称:go-dwmstatus,代码行数:7,代码来源:dwmstatus.go


示例14: collectHostStatistics

func (node mgmNode) collectHostStatistics(out chan mgm.HostStat) {
	for {
		//start calculating network sent
		fInet, err := psnet.NetIOCounters(false)
		if err != nil {
			node.logger.Error("Error reading networking", err)
		}

		s := mgm.HostStat{}
		s.Running = true
		c, err := pscpu.CPUPercent(time.Second, true)
		if err != nil {
			node.logger.Error("Error readin CPU: ", err)
		}
		s.CPUPercent = c

		v, err := psmem.VirtualMemory()
		if err != nil {
			node.logger.Error("Error reading Memory", err)
		}
		s.MEMTotal = v.Total / 1000
		s.MEMUsed = (v.Total - v.Available) / 1000
		s.MEMPercent = v.UsedPercent

		lInet, err := psnet.NetIOCounters(false)
		if err != nil {
			node.logger.Error("Error reading networking", err)
		}
		s.NetSent = (lInet[0].BytesSent - fInet[0].BytesSent)
		s.NetRecv = (lInet[0].BytesRecv - fInet[0].BytesRecv)

		out <- s
	}
}
开发者ID:bitzend,项目名称:mgm,代码行数:34,代码来源:node.go


示例15: Collect

// Collect collects stats related to resource usage of a host
func (h *HostStatsCollector) Collect() (*HostStats, error) {
	hs := &HostStats{Timestamp: time.Now().UTC().UnixNano()}
	if memStats, err := mem.VirtualMemory(); err == nil {
		ms := &MemoryStats{
			Total:     memStats.Total,
			Available: memStats.Available,
			Used:      memStats.Used,
			Free:      memStats.Free,
		}
		hs.Memory = ms
	}

	if cpuStats, err := cpu.Times(true); err == nil {
		cs := make([]*CPUStats, len(cpuStats))
		for idx, cpuStat := range cpuStats {
			cs[idx] = &CPUStats{
				CPU:    cpuStat.CPU,
				User:   cpuStat.User,
				System: cpuStat.System,
				Idle:   cpuStat.Idle,
			}
			percentCalculator, ok := h.statsCalculator[cpuStat.CPU]
			if !ok {
				percentCalculator = NewHostCpuStatsCalculator()
				h.statsCalculator[cpuStat.CPU] = percentCalculator
			}
			idle, user, system, total := percentCalculator.Calculate(cpuStat)
			cs[idx].Idle = idle
			cs[idx].System = system
			cs[idx].User = user
			cs[idx].Total = total
		}
		hs.CPU = cs
	}

	if partitions, err := disk.Partitions(false); err == nil {
		var diskStats []*DiskStats
		for _, partition := range partitions {
			if usage, err := disk.Usage(partition.Mountpoint); err == nil {
				ds := DiskStats{
					Device:            partition.Device,
					Mountpoint:        partition.Mountpoint,
					Size:              usage.Total,
					Used:              usage.Used,
					Available:         usage.Free,
					UsedPercent:       usage.UsedPercent,
					InodesUsedPercent: usage.InodesUsedPercent,
				}
				diskStats = append(diskStats, &ds)
			}
		}
		hs.DiskStats = diskStats
	}

	if uptime, err := host.Uptime(); err == nil {
		hs.Uptime = uptime
	}
	return hs, nil
}
开发者ID:iverberk,项目名称:nomad,代码行数:60,代码来源:host.go


示例16: GetRenderContext

func GetRenderContext() *mem.VirtualMemoryStat {
	if avg, err := mem.VirtualMemory(); err == nil {
		return avg
	} else {
		log.Fatal(err)
	}
	return nil
}
开发者ID:andir,项目名称:go3status,代码行数:8,代码来源:memory.go


示例17: GetMemStats

func GetMemStats() string {
	v, err := mem.VirtualMemory()
	format := "total=%d available=%d used=%d used_percent=%f"
	if err == nil {
		return fmt.Sprintf(format, v.Total, v.Available, v.Used, v.UsedPercent)
	} else {
		return fmt.Sprintf(format, 0, 0, 0, 0)
	}
}
开发者ID:lightspeedretail,项目名称:stats-ag,代码行数:9,代码来源:corestats.go


示例18: GetInfo

func GetInfo() map[string]interface{} {
	path := "/"
	if runtime.GOOS == "windows" {
		file, _ := exec.LookPath(os.Args[0])
		path = filepath.VolumeName(file)
	}

	diskinfo := disk.UsageStat{}
	if v, err := disk.Usage(path); err == nil {
		var i interface{}
		i = v
		switch inst := i.(type) {
		case disk.UsageStat:
			diskinfo = inst
			break
		case *disk.UsageStat:
			if inst != nil {
				diskinfo = *inst
			}
			break
		}

	}
	diskinfo.Total /= 1024 * 1024
	diskinfo.Used /= 1024 * 1024

	vm := mem.VirtualMemoryStat{}
	sm := mem.SwapMemoryStat{}

	if v, err := mem.VirtualMemory(); err == nil {
		vm = *v
	}
	vm.Total /= 1024 * 1024
	vm.Used /= 1024 * 1024
	if v, err := mem.SwapMemory(); err == nil {
		sm = *v
	}
	sm.Total /= 1024 * 1024
	sm.Used /= 1024 * 1024

	var cpupercent float64

	ps, err := cpu.Percent(time.Millisecond, true)
	if err == nil && len(ps) > 0 {
		for _, v := range ps {
			cpupercent += v
		}
		cpupercent /= float64(len(ps))
	}

	return map[string]interface{}{
		"DiskInfo":      diskinfo,
		"SwapMemory":    sm,
		"VirtualMemory": vm,
		"CpuPercent":    cpupercent * 100,
	}
}
开发者ID:mysll,项目名称:flynet,代码行数:57,代码来源:info.go


示例19: getMemoryUsage

func getMemoryUsage() (float32, float32) {
	v, err := mem.VirtualMemory()
	if err != nil {
		log.Printf("ERROR: Unable to get memory usage for the scout.")
		log.Print(err)
	}

	return float32(v.Total), (float32(v.UsedPercent) / 100.0)
}
开发者ID:MeasureTheFuture,项目名称:scout,代码行数:9,代码来源:heartbeat.go


示例20: main

func main() {
	memSt, err := mem.VirtualMemory()
	if err != nil {
		log.Panicln(err)
	}

	log.Println("Total: ", memSt.Total)
	log.Println("Free: ", memSt.Free)
	log.Println("Used:", memSt.Used)
}
开发者ID:upccup,项目名称:cuplearn,代码行数:10,代码来源:mem.go



注:本文中的github.com/shirou/gopsutil/mem.VirtualMemory函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang process.NewProcess函数代码示例发布时间:2022-05-28
下一篇:
Golang load.LoadAvg函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap