当前位置: 首页>>代码示例>>Golang>>正文


Golang mem.VirtualMemory函数代码示例

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


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


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