如何减少CPU使用率?

时间:2019-01-22 11:34:06

标签: windows-10 cpu-usage go

我正在开发一个应用程序,该程序监视与系统有关的事物CPU,RAM等。即使在测试期间数据很少,我发现只要我运行代码,每次轮询数据后,CPU使用率通常都会出现30%的峰值。恢复正常。 因此,有什么方法可以减少这种峰值。

代码如下:

package main

import (
    "fmt"
    "github.com/shirou/gopsutil/cpu"
    "github.com/shirou/gopsutil/mem"
    "github.com/shirou/gopsutil/process"
    "github.com/shirou/gopsutil/load"
    "github.com/shirou/gopsutil/disk"
    "github.com/shirou/gopsutil/host"
    "reflect"
    "time"
)

func main() {

    driveC := "C:"

    processor, _ := cpu.Times(false)
    memory,_ := mem.VirtualMemory()
    cpuPercent,_ := cpu.Percent(time.Second,false)



    fmt.Println(reflect.TypeOf(processor))
    fmt.Println(reflect.TypeOf(memory))
    fmt.Println(reflect.TypeOf(cpuPercent))


    fmt.Println("CPU")
    fmt.Println("CPU name",processor[0].CPU)
    fmt.Println("User time",processor[0].User)
    fmt.Println("Idle time",processor[0].Idle)
    fmt.Println("System time",processor[0].System)
    fmt.Println("Nice time",processor[0].Nice)
    fmt.Println("IOwait time",processor[0].Iowait)
    fmt.Println("Irq time",processor[0].Irq)
    fmt.Println("SoftIrq time",processor[0].Softirq)



    fmt.Println("CPU Percent",cpuPercent)
    //fmt.Println(memory.Total)


    infoStat, _ := cpu.Info()
    fmt.Printf("\n")
    fmt.Println("--> Hardware Info with Context:  ", infoStat)

    procCount, _ := cpu.ProcInfo()
    fmt.Printf("\n")
    fmt.Println("--> Process Count:  ", procCount)

    fmt.Println("-----------------DISK--------------------------------->")

    driveUsage, _ := disk.Usage(driveC)
    fmt.Printf("\n")
    fmt.Println("--> Disk Usage for :", driveUsage)

    partitionInfo, _ := disk.Partitions(true)
    fmt.Printf("\n")
    fmt.Println("--> Partitions :", partitionInfo)

    folderInfo, _ := disk.IOCounters("C:", "D:")
    //fmt.Printf("\nDisk IO counter remaining\n")
    fmt.Printf("\n")
    fmt.Println("-->Disk IO counter :", folderInfo)

    fmt.Printf("Docker remaining\n")
    fmt.Printf("\n")

    fmt.Println("-----------------Host--------------------------------->")

    hostInfo, _ := host.Info()
    fmt.Printf("\n")
    fmt.Println("--> Host Info :", hostInfo)

    /*userName, _ := host.Users()
    fmt.Printf("\n")
    fmt.Println("--> Username :", userName)*/

    fmt.Println("-----------------Load--------------------------------->")

    avgLoad, _ := load.Avg()
    fmt.Printf("\n")
    fmt.Println("--> Average Load :", avgLoad)

    avgMisc, _ := load.Misc()
    fmt.Printf("\n")
    fmt.Println("--> Misc :", avgMisc)

    fmt.Println("-----------------RAM--------------------------------->")

    virtMemory, _ := mem.VirtualMemory()
    fmt.Printf("\n")
    fmt.Println("--> Virtual Memory :", virtMemory)

    swapMemory, _ := mem.SwapMemory()
    fmt.Printf("\n")
    fmt.Println("--> Swap Memory :", swapMemory)

    //fmt.Println("Process running list")
    //processList()

}

OS-Windows 10, 编程语言-Golang

0 个答案:

没有答案