在执行`make()`语句之前如何确定可用内存?

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

How to determine available memory before a make() statement

问题

在Go语言中,当使用make语句时,例如分配几兆字节的内存:

make([]byte, 10241024d)

有没有一种方法可以在请求更多内存之前确定有多少可用内存?

英文:

In Go, when using a make statement,
for example, allocating megabytes of memory

    make([]byte, 1024*1024*d)

Is there a way to determine how much memory is free, before asking for more memory?

答案1

得分: 1

感谢您提供的所有意见。

我决定使用Max_Memory配置选项,因为这个用例是在测试服务器上利用n兆字节的内存,最多使用可用内存的75%,这些服务器只运行这个应用程序,作为在测试环境中触发自动扩展的一种方式。

英文:

Thank you for all your input.

I have decided to use a Max_Memory configuration option, since the use case for this is to utilize n Megabytes of memory up to about 75% max available, on test servers, which are only running this application, as a way to trigger autoscaling in a test environment.

答案2

得分: 0

是的,有的。你可以使用gopsutil包:

package main

import (
	"fmt"

	"github.com/shirou/gopsutil/mem"
)

func main() {
	vm, err := mem.VirtualMemory()
	if err != nil {
		panic(err)
	}
	fmt.Printf("Total:%d, Available:%d, Used:%d", vm.Total, vm.Available, vm.Used)
}

还有很多获取这些信息的特定于操作系统的方法。虽然它们都不是完美的,但它们会给你一些信息。

你还可以将最大内存作为配置变量,并使用:http://godoc.org/runtime#MemStats。

英文:

Yes there is. You can use the gopsutil package:

package main

import (
	"fmt"

	"github.com/shirou/gopsutil/mem"
)

func main() {
	vm, err := mem.VirtualMemory()
	if err != nil {
		panic(err)
	}
	fmt.Printf("Total:%d, Available:%d, Used:%d", vm.Total, vm.Available, vm.Used)
}

There are also lots of ways to get this information that are OS-specific. None of them are perfect, but they'll give you something.

You could also have Max Memory as a configuration variable and use: http://godoc.org/runtime#MemStats.

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

发表评论

匿名网友

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

确定