如何计算Java程序的内存使用率? [英] How to calculate memory usage of a Java program?

查看:784
本文介绍了如何计算Java程序的内存使用率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用Runtime类(freeMemory()totalMemory()gc()),那么它将为我提供MB以上的内存(即1,000,000字节).

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

但是,如果我在任何在线编译器上运行相同的代码,则它们将显示以KB为单位的内存(即1000字节).这是巨大的差异.

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.

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

This means Runtime does not show the actual memory used by the program.

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

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?

推荐答案

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

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.

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

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

  • 记住它,那个Runtime.getRuntime().totalMemory()这个内存 是您的JVM可用的总内存.
  • java -Xms512m -Xmx1024m ,表示程序的总内存 将从512MB开始,可能会延迟加载至最大1024MB.
  • 因此,如果您在不同的JVM上运行相同的程序, Runtime.getRuntime().totalMemory()可能会给您不同的结果.
  • 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.

这篇关于如何计算Java程序的内存使用率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆