2011-05-03 35 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)); 
    } 
}