【问题标题】:program run time (in a loop, only displayed once)程序运行时间(循环,只显示一次)
【发布时间】:2023-03-24 02:40:01
【问题描述】:

我想在代码中测量程序运行时间(只有搜索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,所以屏幕显示 4x exec time。

【问题讨论】:

    标签: java multithreading time thread-safety


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      只需将这两行代码移出 for 循环即可:

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

      【讨论】:

        猜你喜欢
        • 2018-05-02
        • 1970-01-01
        • 2011-11-02
        • 2013-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-10
        • 2020-03-05
        相关资源
        最近更新 更多