如何计算 Java 程序的内存使用量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37916136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:47:26  来源:igfitidea点击:

How to calculate memory usage of a Java program?

javamemory-managementruntime

提问by Ganesh S

If I use the Runtimeclass (freeMemory(), totalMemory(), and gc()), then it gives me memory above MB (i.e. 1,000,000 bytes).

如果我使用Runtime类(freeMemory()totalMemory()gc()),那么它给我的内存超过 MB(即 1,000,000 字节)。

But if I run the same code on any online compiler, then they show memory used in KB (i.e. 1000 bytes). This is a huge difference.

但是如果我在任何在线编译器上运行相同的代码,那么它们会以 KB(即 1000 字节)显示使用的内存。这是一个巨大的差异。

This means Runtimedoes not show the actual memory used by the program.

这意味着Runtime不显示程序使用的实际内存。

I need to calculate actual memory used by the program. What is the way these online compilers use to calculate memory used by the program?

我需要计算程序使用的实际内存。这些在线编译器用于计算程序使用的内存的方式是什么?

采纳答案by Amit Bhati

First calculate the memory used before your code execution i.e. first line of your code.

首先计算代码执行前使用的内存,即代码的第一行。

long beforeUsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();

Calculate the memory used after your code execution:-

计算代码执行后使用的内存:-

long afterUsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();

Then you can do:

然后你可以这样做:

long actualMemUsed=afterUsedMem-beforeUsedMem;

It will give you actual memory utilized by your program.

它将为您提供程序使用的实际内存。

For further memory analysis your best bet is any profiler tool like jvisualvm.

对于进一步的内存分析,您最好的选择是任何分析器工具,例如jvisualvm

  • Do remember it, that Runtime.getRuntime().totalMemory(), this memory is total memory available to your JVM.
  • java -Xms512m -Xmx1024m, it means that total memory of your program will start with 512MB, which may lazily loaded to max of 1024MB.
  • So if you are running same program, on different JVMs, Runtime.getRuntime().totalMemory() might give you different results.
  • 请记住,Runtime.getRuntime().totalMemory(),此内存是您的 JVM 可用的总内存。
  • java -Xms512m -Xmx1024m,这意味着您的程序的总内存将从 512MB 开始,这可能会延迟加载到最大 1024MB。
  • 因此,如果您在不同的 JVM 上运行相同的程序, Runtime.getRuntime().totalMemory() 可能会给您不同的结果。

回答by Rohit Gupta

You can use topcommand in ubuntu to check % CPU use or % memory use while running the java programme.

您可以在 ubuntu 中使用top命令来检查运行 java 程序时的 CPU 使用率或内存使用率。

top command will give you these many information.

top 命令将为您提供这些信息。

PIDUSERPRNIVIRTRESSHRS%CPU%MEMTIME+ COMMAND

PIDUSERPRNIVIRTRESSHRS%CPU%MEMTIME+ COMMAND

just type topand hit enter in your terminal & check java in command section.

只需 top在终端中输入并按回车键并在命令部分检查 java。