java - 一个合适的基准?

标签 java multithreading benchmarking

我想测量 2 个不同的程序执行 1 个任务需要多长时间。一个程序使用了线程,另一个没有。任务是数到 2000000。

线程类:

public class Main {
    private int res1 = 0;
    private int res2 = 0;

    public static void main(String[] args) {
        Main m = new Main();

        long startTime = System.nanoTime();
        m.func();
        long endTime = System.nanoTime();

        long duration = endTime - startTime;
        System.out.println("duration: " + duration);
    }

    public void func() {
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 1000000; i++) {
                    res1++;
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 1000000; i < 2000000; i++) {
                    res2++;
                }
            }
        });

        t1.start();
        t2.start();

        System.out.println(res1 + res2);
    }
}

没有线程:

public class Main {

    private int res = 0;

    public static void main(String[] args) {
        Main m = new Main();

        long startTime = System.nanoTime();
        m.func();
        long endTime = System.nanoTime();

        long duration = endTime - startTime;
        System.out.println("duration: " + duration);

    }

    public void func() {

        for (int i = 0; i < 2000000; i++) {
            res++;
        }
        System.out.println(res);
    }
}

10 次测量后的平均结果(以纳秒为单位)为:

With threads:    1952358
Without threads: 7941479

我做的对吗?
为什么使用 2 个线程时速度提高了 4 倍而不是 2 倍?

最佳答案

行内

    t1.start();
    t2.start();

您正在开始线程执行,但您实际上并没有在进行时间测量之前等待它们完成。要等到线程完成,请调用

   t1.join();
   t2.join();

join 方法将阻塞直到线程结束。然后测量执行时间。

关于java - 一个合适的基准?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14308805/

相关文章:

c++ - 使函数线程安全与否?

MySQL BIGINT(20) 与 Varchar(31) 性能对比

java - 数组应该比 ArrayList 快这么多吗?

java - 为什么 IntStream.range(0, 100000).parallel().foreach 需要比正常循环更长的时间

java - 如何在网站不宕机的情况下替换实时服务器上的 war 文件

java - JPA (Hibernate) 和自定义表前缀

java - 在notify()之后线程不恢复执行

c++ - 使用 Boost.Lockfree 队列比使用互斥锁慢

java - 是否可以在 Spring Boot 中的两个方法之间传递模型值?

java - 关闭主 JFrame