【问题标题】:test memory consumption of a java program with eclipse [closed]用eclipse测试java程序的内存消耗[关闭]
【发布时间】:2011-08-17 16:28:31
【问题描述】:

eclipse 中是否有一个插件可以用来测试我刚刚运行的程序花费了多少内存?

我想在我运行程序后可能有一个来自插件的按钮,我可以点击它,它会显示我的程序的峰值内存消耗图表。

【问题讨论】:

    标签: java eclipse memory plugins monitor


    【解决方案1】:

    我个人喜欢 VisualVM (tutorial),它包含在最新的 JDK 版本中。

    【讨论】:

    • 我用VisualVM附加了默认启动器,一切正常,但是如果我启动一个java代码,在VisualVIM的local部分会显示一个未知的应用程序,当代码退出时,未知应用程序也消失了,如何保留过去运行的程序的分析结果?
    • 试试Snapshots。
    【解决方案2】:

    我同意 Mr.Nobody 的观点,即 VisualVM 很好。 Eclipse Memory Analyzer 也有一些不错的功能。

    【讨论】:

      【解决方案3】:

      程序的total used / free memory可以通过java.lang.Runtime.getRuntime()在程序中获取;

      运行时有几个与内存相关的方法。下面的代码示例演示了它的用法。

      import java.util.ArrayList;
      import java.util.List;
      
      public class PerformanceTest {
        private static final long MEGABYTE = 1024L * 1024L;
      
        public static long bytesToMegabytes(long bytes) {
          return bytes / MEGABYTE;
        }
      
        public static void main(String[] args) {
          // I assume you will know how to create an object Person yourself...
          List<Person> list = new ArrayList<Person>();
          for (int i = 0; i <= 100000; i++) {
            list.add(new Person("Jim", "Knopf"));
          }
          // Get the Java runtime
          Runtime runtime = Runtime.getRuntime();
          // Run the garbage collector
          runtime.gc();
          // Calculate the used memory
          long memory = runtime.totalMemory() - runtime.freeMemory();
          System.out.println("Used memory is bytes: " + memory);
          System.out.println("Used memory is megabytes: "
              + bytesToMegabytes(memory));
        }
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-21
        • 1970-01-01
        • 1970-01-01
        • 2017-05-28
        • 2019-02-21
        相关资源
        最近更新 更多