How to set memory limit while running golang application in local system

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

How to set memory limit while running golang application in local system

问题

我想在我的Windows机器上为Go应用程序设置堆大小。

在Java中,我们通常在IntelliJ中提供-Xms设置作为虚拟机参数,但是如何在Go语言中提供类似的设置并为Go应用程序设置内存限制呢?

我尝试了以下方法:

<env name="GOMEMLIMIT" value="2750MiB" />

但是没有起作用。

我们正在使用Go 1.6.2版本。

英文:

i want set heap size for go application in my windows machine

In java we used to provide -Xms settings as vm arguments in intellij but how to provide similar setting in golang and set memory limit for the go application.

Tried with

&lt;env name=&quot;GOMEMLIMIT&quot; value=&quot;2750MiB&quot; /&gt;

but not working

we are using go 1.6.2 version.

答案1

得分: 2

Go 1.19增加了对软内存限制的支持:

运行时现在包括对软内存限制的支持。这个内存限制包括Go堆和运行时管理的所有其他内存,但不包括二进制文件本身的映射、其他语言管理的内存以及操作系统代表Go程序持有的内存等外部内存来源。可以通过runtime/debug.SetMemoryLimit或等效的GOMEMLIMIT环境变量来管理此限制。

你不能设置一个硬限制,因为这会导致你的应用程序在需要更多内存时发生故障。

要从应用程序中设置软限制,只需使用以下代码:

debug.SetMemoryLimit(2750 * 1 << 20) // 2750 MB

要在应用程序外部设置软限制,使用GOMEMLIMIT环境变量,例如:

GOMEMLIMIT=2750MiB

但请注意,这样做可能会降低应用程序的性能,因为它可能会更频繁地进行垃圾回收,并更积极地将内存返回给操作系统,即使应用程序将再次需要它。

英文:

Go 1.19 adds support for a soft memory limit:

> The runtime now includes support for a soft memory limit. This memory limit includes the Go heap and all other memory managed by the runtime, and excludes external memory sources such as mappings of the binary itself, memory managed in other languages, and memory held by the operating system on behalf of the Go program. This limit may be managed via runtime/debug.SetMemoryLimit or the equivalent GOMEMLIMIT environment variable.

You can't set a hard limit as that would make your app malfunction if it would need more memory.

To set a soft limit from your app, simply use:

debug.SetMemoryLimit(2750 * 1 &lt;&lt; 20) // 2750 MB

To set a soft limit outside of your app, use the GOMEMLIMIT env var, e.g.:

GOMEMLIMIT=2750MiB

But please note that doing so may make your app's performance worse as it may enforce more frequent garbage collection and return memory to OS more aggressively even if your app will need it again.

huangapple
  • 本文由 发表于 2022年9月8日 16:39:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/73646060.html
匿名

发表评论

匿名网友

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

确定