github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/util/profile.go (about)

     1  package util
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  	"time"
     7  
     8  	"github.com/shirou/gopsutil/v3/cpu"
     9  	"github.com/shirou/gopsutil/v3/disk"
    10  	"github.com/shirou/gopsutil/v3/mem"
    11  )
    12  
    13  const (
    14  	Cpu       = "cpu"
    15  	Memory    = "mem"
    16  	Disk      = "disk"
    17  	Goroutine = "goroutine"
    18  )
    19  
    20  func GetCpuPercent() (float64, *Err) {
    21  	percent, e := cpu.Percent(time.Second, false)
    22  	if e != nil {
    23  		return 0, WrapErr(EcServiceErr, e)
    24  	}
    25  	return percent[0], nil
    26  }
    27  
    28  func GetMemPercent() float64 {
    29  	memInfo, _ := mem.VirtualMemory()
    30  	return memInfo.UsedPercent
    31  }
    32  
    33  func GetDiskPercent() float64 {
    34  	parts, _ := disk.Partitions(true)
    35  	diskInfo, _ := disk.Usage(parts[0].Mountpoint)
    36  	return diskInfo.UsedPercent
    37  }
    38  
    39  func StartProfile(dur time.Duration, receiver chan<- M) {
    40  	go func() {
    41  		sampling(receiver)
    42  		ticker := time.NewTicker(dur)
    43  		for {
    44  			select {
    45  			case <-_Ctx.Done():
    46  				ticker.Stop()
    47  				return
    48  			case <-ticker.C:
    49  				sampling(receiver)
    50  			}
    51  		}
    52  	}()
    53  }
    54  
    55  func sampling(receiver chan<- M) {
    56  	status := M{
    57  		Memory:    float32(GetMemPercent()),
    58  		Disk:      float32(GetDiskPercent()),
    59  		Goroutine: uint32(runtime.NumGoroutine()),
    60  	}
    61  	if runtime.GOOS != "darwin" { //暂时不支持
    62  		cp, err := GetCpuPercent()
    63  		if err == nil {
    64  			status[Cpu] = float32(cp)
    65  		} else {
    66  			fmt.Println("get cpu fail:")
    67  			fmt.Println(err.Error())
    68  		}
    69  	}
    70  	receiver <- status
    71  }