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