本文整理汇总了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))
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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)
}
}
}
示例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)
}
}
示例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)
}
示例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)
}
}
示例11: updateMemory
func updateMemory() {
v, err = mem.VirtualMemory()
log.Printf("updateMemory(): %v", spew.Sdump(v))
if err != nil {
log.Fatal(err)
}
}
示例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))
}
}
示例13: memory
func memory() string {
v, err := mem.VirtualMemory()
if err != nil {
log.Println(err)
}
return fmt.Sprintf("%3d%%", int(v.UsedPercent))
}
示例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
}
}
示例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
}