我想测量 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/