How to get total memory/RAM in GO?

huangapple go评论79阅读模式
英文:

How to get total memory/RAM in GO?

问题

你好!以下是你要翻译的内容:

如何在Go语言中获取系统上附加的总内存/ RAM量?如果可能的话,我希望只使用本地代码。我找到了一个封装了Linux sysinfo命令的库。是否有更加优雅的方法?

英文:

How can I get the total amount of memory/RAM attached to a system in Go? I want to use native code only if possible. I have found a library that wraps linux sysinfo command. Is there a more elegant way?

答案1

得分: 16

你好!以下是你要求的代码的中文翻译:

package main

// #include <unistd.h>
import "C"

func main() {
    println(C.sysconf(C._SC_PHYS_PAGES) * C.sysconf(C._SC_PAGE_SIZE), " 字节")
}

希望对你有帮助!如果你有任何其他问题,请随时提问。

英文:

cgo & linux solution

package main

// #include &lt;unistd.h&gt;
import &quot;C&quot;

func main() {
    println(C.sysconf(C._SC_PHYS_PAGES)*C.sysconf(C._SC_PAGE_SIZE), &quot; bytes&quot;)
}

答案2

得分: 14

除了runtime.MemStats之外,您还可以使用gosigar来监视系统内存。

英文:

Besides runtime.MemStats you can use gosigar to monitor system memory.

答案3

得分: 2

在我的研究中,我发现了一个名为memory package的项目,它在许多不同的平台上实现了这个功能。如果你正在寻找一个快速简便的解决方案而不需要CGO,这可能是你最好的选择。

从README文件中可以看到以下代码示例:

package main

import (
	"fmt"
	"github.com/pbnjay/memory"
)

func main() {
	fmt.Printf("Total system memory: %d\n", memory.TotalMemory())
}

Go Playground上运行结果为:

Total system memory: 104857600
英文:

In my research on this I came across the memory package that implements this for a number of different platforms. If you're looking for a quick and easy solution without CGO, this might be your best option.

From the README:

package main

import (
	&quot;fmt&quot;
	&quot;github.com/pbnjay/memory&quot;
)

func main() {
	fmt.Printf(&quot;Total system memory: %d\n&quot;, memory.TotalMemory())
}

On go Playground:

Total system memory: 104857600

答案4

得分: 2

你可以直接在Go程序中读取*/proc/meminfo*文件,就像@Intermerne建议的那样。
例如,你可以定义如下的结构体:

type Memory struct {
    MemTotal     int
    MemFree      int
    MemAvailable int
}

然后,你可以从*/proc/meminfo*中填充这个结构体:

func ReadMemoryStats() Memory {
    file, err := os.Open("/proc/meminfo")
    if err != nil {
        panic(err)
    }
    defer file.Close()
    scanner := bufio.NewScanner(file)
    res := Memory{}
    for scanner.Scan() {
        key, value := parseLine(scanner.Text())
        switch key {
        case "MemTotal":
            res.MemTotal = value
        case "MemFree":
            res.MemFree = value
        case "MemAvailable":
            res.MemAvailable = value
        }
    }
    return res
}

下面是解析单行的代码(但我认为可以更高效地完成):

func parseLine(raw string) (key string, value int) {
    fmt.Println(raw)
    text := strings.ReplaceAll(raw[:len(raw)-2], " ", "")
    keyValue := strings.Split(text, ":")
    return keyValue[0], toInt(keyValue[1])
}

func toInt(raw string) int {
    if raw == "" {
        return 0
    }
    res, err := strconv.Atoi(raw)
    if err != nil {
        panic(err)
    }
    return res
}

你可以从文档中了解更多关于*/proc/meminfo*的信息。

英文:

You can read /proc/meminfo file directly in your Go program, as @Intermerne suggests.
For example, you have the next structure:

type Memory struct {
	MemTotal     int
	MemFree      int
	MemAvailable int
}

You can just fill structure from the /proc/meminfo:

func ReadMemoryStats() Memory {
	file, err := os.Open(&quot;/proc/meminfo&quot;)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	bufio.NewScanner(file)
	scanner := bufio.NewScanner(file)
	res := Memory{}
	for scanner.Scan() {
		key, value := parseLine(scanner.Text())
		switch key {
		case &quot;MemTotal&quot;:
			res.MemTotal = value
		case &quot;MemFree&quot;:
			res.MemFree = value
		case &quot;MemAvailable&quot;:
			res.MemAvailable = value
		}
	}
	return res
}

Here is a code of parsing separate line (but I think it could be done more efficiently):

func parseLine(raw string) (key string, value int) {
	fmt.Println(raw)
	text := strings.ReplaceAll(raw[:len(raw)-2], &quot; &quot;, &quot;&quot;)
	keyValue := strings.Split(text, &quot;:&quot;)
	return keyValue[0], toInt(keyValue[1])
}

func toInt(raw string) int {
	if raw == &quot;&quot; {
		return 0
	}
	res, err := strconv.Atoi(raw)
	if err != nil {
		panic(err)
	}
	return res
}

More about "/proc/meminfo" you can read from the documentation

huangapple
  • 本文由 发表于 2015年5月4日 09:19:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/30021296.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定