2

假设我在 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;
            }
        }
    }
}
}

有没有办法查出

(a) 元素数组的数据结构消耗多少 RAM?

(b) 如果没有 - 有没有办法比较该进程与普通 HelloWorld 相比消耗了多少 RAM?

package testing;

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

}
4

4 回答 4

1

元素数组的数据结构消耗多少 RAM?

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

如果没有 - 有没有办法比较该进程与普通 HelloWorld 相比消耗了多少 RAM?

猜测一下,我会说您的第一个示例比第二个示例使用多达 100 KB。int这是因为在加载额外的类并将值转换String为大部分内存消耗的感觉背后进行分配。相比之下,您的数组微不足道。

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

于 2012-08-29T11:24:39.207 回答
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();
于 2012-08-29T11:26:21.740 回答
0

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

调用所有 GC 不会给你带来“真实”的结果。VM本身分配了很多对象。可能会被清理,你会得到错误的图片。

于 2012-08-29T11:31:52.110 回答
0

使用这个公式;

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

     static final Runtime runtime = Runtime.getRuntime();
于 2012-08-29T11:35:30.430 回答