program 运行 时间(循环,只显示一次)

program run time (in a loop, only displayed once)

我想在代码中测量程序运行的时间(仅搜索min和max的时间),我的问题是搜索min和max在循环中,并且运行 时间也显示了循环中的 x 倍,因为我可以测量循环中的时间并在屏幕上只显示一个结果?

 long realTime = System.currentTimeMillis();
        for (int i = 0; i < PARTITIONS; i++) {
            final int partition = i;
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    // find min,max
                    int from = arrayToSearch.length * partition / PARTITIONS;
                    int to = arrayToSearch.length * (partition + 1) / PARTITIONS;
                    int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
                    for (int j = from; j < to; j++) {
                        min = Math.min(min, arrayToSearch[j]);
                        max = Math.max(max, arrayToSearch[j]);
                    }
                    partitionMin[partition] = min;
                    partitionMax[partition] = max;
                    long execcutionTime = System.currentTimeMillis() - realTime;
                    System.out.println("exec time: " + execcutionTime + "ms");
                }

            });

在此程序中,PARTITIONS = 4,因此屏幕显示 4 倍的执行时间。

只需将这两行代码放在 for 循环之外:

long execcutionTime = System.currentTimeMillis() - realTime; System.out.println("exec time: " + execcutionTime + "ms");

好吧,如果你不关心显示哪个结果,那么最简单的方法是仅当 partition 为 0 时才打印执行时间,如下所示:

if (partition == 0) {
    System.out.println("exec time: " + execcutionTime + "ms");
}