在Java中查找操作占用的内存

在Java中查找操作占用的内存,java,memory-management,Java,Memory Management,假设我在Java中执行如下气泡排序示例: package testing; public class bubbleSort { public static void main(String a[]) { int i; int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 }; System.out.println("Values Before the sort:\n"); for (i = 0; i < array.len

假设我在Java中执行如下气泡排序示例:

package testing;

public class bubbleSort {
public static void main(String a[]) {
    int i;
    int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 };
    System.out.println("Values Before the sort:\n");
    for (i = 0; i < array.length; i++)
        System.out.print(array[i] + "  ");
    System.out.println();
    bubble_srt(array, array.length);
    System.out.print("Values after the sort:\n");
    for (i = 0; i < array.length; i++)
        System.out.print(array[i] + "  ");
    System.out.println();
    System.out.println("PAUSE");
}

public static void bubble_srt(int a[], int n) {
    int i, j, t = 0;
    for (i = 0; i < n; i++) {
        for (j = 1; j < (n - i); j++) {
            if (a[j - 1] > a[j]) {
                t = a[j - 1];
                a[j - 1] = a[j];
                a[j] = t;
            }
        }
    }
}
}
元素数组的数据结构消耗了多少RAM

不容易。它大约有40-48字节长,不值得担心

如果没有-有没有一种方法可以比较该进程与普通HelloWorld相比消耗了多少RAM

package testing;

public class Testing {
public static void main(String[] args) {
    System.out.println("Hello World!");
}

}
我猜,您的第一个示例比第二个示例多使用100 KB。这是因为在加载额外类并将
int
值转换为
String
这是内存消耗的主要部分的意义后面存在分配。相比之下,您的数组微不足道


无论如何,100KB也不值得担心。在桌面上,100 KB的成本不到1美分,并且可以重复使用。

您可以使用
getRunTime()
查找当前程序的运行时。而
totalmemory
属性将帮助您找到所使用的内存

   // Get the Java runtime
    Runtime runtime = Runtime.getRuntime();
    // Run the garbage collector
    runtime.gc();
    // Calculate the used memory
    long memory = runtime.totalMemory() - runtime.freeMemory();

您必须对应用程序进行概要分析,以获得实际的内存使用情况。尝试在调用sort之前向应用程序添加暂停。在运行排序之前和排序完成之后创建内存快照,并进行比较

调用所有GC不会带来“真实”的结果。虚拟机本身分配了很多对象。这张照片可能会被清洗,你会得到错误的图片

使用这个公式

     static long memoryUsed() {
        return runtime.totalMemory() - runtime.freeMemory();
     }

     static final Runtime runtime = Runtime.getRuntime();

对于小对象,这几乎总是
0
。它也可以是负数。嗨,彼得,你能扩展一下吗?对于小对象,这几乎总是0。它也可以是负数。如何得到所用字节数的估计值?一个8-16字节的头,有8 x 4字节(int使用4字节)