chatGPT答: |
8v6.cn |
百分比和已使用内存的程序
```go
package main
import (
"fmt"
"os"
"runtime"
"strings"
"strconv"
)
func main() {
// 获取当前操作系统的类型,仅支持linux、windows
osType := runtime.GOOS
if osType != "linux" && osType != "windows" {
fmt.Println("Unsupported operating system:" + osType)
os.Exit(-1)
}
if osType == "linux" {
// linux内存使用情况
mem := getLinuxMemInfo()
total := mem["MemTotal"]
used := mem["MemUsed"]
// 计算内存使用率
rate := float64(used) / float64(total)
// 输出内存使用率和已使用内存
fmt.Printf("used:%dK\tuse rate:%.2f%%\n", used, rate*100)
} else {
// windows内存使用情况
mem := getWindowsMemInfo()
used := mem["MemUsed"]
total := mem["MemTotal"]
// 计算内存使用率
rate := float64(used) / float64(total)
// 输出内存使用率和已使用内存
fmt.Printf("used:%dK\tuse rate:%.2f%%\n", used, rate*100)
}
}
// 获取Linux内存使用情况
func getLinuxMemInfo() map[string]int {
// 将命令的标准输出结果存到data中
data, err := readFileToString("/proc/meminfo")
if err != nil {
fmt.Println("read meminfo failed:", err.Error())
os.Exit(-1)
}
// 返回结果map
mem := make(map[string]int)
lines := strings.Split(data, "\n")
for _, line := range lines {
parts := strings.Split(line, ":")
if len(parts) != 2 {
continue
}
// 获取键和值
key := strings.trimSpace(parts[0])
value := strings.trimSpace(parts[1])
unit := strings.trimSpace(value[len(value)-1:])
value = strings.trimSpace(value[:len(value)-1])
// 将单位为KB的值转换成int
intValue,err := strconv.Atoi(value)
if err != nil {
continue
}
if unit == "kB" {
mem[key] = intValue * 1024
continue
}
mem[key] = intValue
}
return mem
}
// 获取Windows内存使用情况
func getWindowsMemInfo() map[string]int {
data, err := readFileToString("C:/meminfo.txt")
if err != nil {
fmt.Println("read meminfo failed:", err.Error())
os.Exit(-1)
}
// 返回结果map
mem := make(map[string]int)
lines := strings.Split(data, "\n")
for _, line := range lines {
parts := strings.Split(line, ":")
if len(parts) != 2 {
continue
}
// 获取键和值
key := strings.trimSpace(parts[0])
value := strings.trimSpace(parts[1])
unit := strings.trimSpace(value[len(value)-1:])
value = strings.trimSpace(value[:len(value)-1])
// 将单位为MB的值转换成int
intValue,err := strconv.Atoi(value)
if err != nil {
continue
}
if unit == "mB" {
mem[key] = intValue * 1024 * 1024
continue
}
mem[key] = intValue
}
return mem
}
// 读取文件的内容并返回字符串
func readFileToString(filename string) (string, error) {
// 打开文件
fd,err := os.Open(filename)
if err != nil {
return "", err
}
defer fd.Close()
// 读取文件内容
bs := make([]byte, 1024)
n, err := fd.Read(bs)
if err != nil {
return "", err
}
// 返回字符串
return string(bs[:n]), nil
}
```
|