2011-05-03 55 views
7

在eclipse中是否有一个插件可以用来测试我的只运行程序成本的内存是多少?我想这个插件可能有一个按钮,在我运行程序后,我可以点击它,它向我展示了一个刚才我的程序的快速内存消耗图。谢谢用eclipse测试java程序的内存消耗

回答

8

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

+0

我附有VisualVM的默认启动,这一切运作良好,但如果我启动一个java代码,在VisualVIM的'local'部分显示了一个未知的应用程序,当程序退出,未知应用程序也消失了,我怎样才能保留过去运行的程序的简介结果? – user685275 2011-05-03 12:59:59

+0

尝试[Snapshots](http://download.oracle.com/javase/6/docs/technotes/guides/visualvm/snapshots.html)。 – 2011-05-03 14:05:23

+0

感谢您的帮助 – user685275 2011-05-03 17:21:36

2

程序中使用/释放的内存总量可以在程序中通过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 a 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)); 
    } 
}