在 Java 中,我有简单的多线程代码:
public class ThreadedAlgo {
public static final int threadsCount = 3;
public static void main(String[] args) {
// start timer prior computation
time = System.currentTimeMillis();
// create threads
Thread[] threads = new Thread[threadsCount];
class ToDo implements Runnable {
public void run() { ... }
}
// create job objects
for (int i = 0; i < threadsCount; i++) {
ToDo job = new ToDo();
threads[i] = new Thread(job);
}
// start threads
for (int i = 0; i < threadsCount; i++) {
threads[i].start();
}
// wait for threads above to finish
for (int i = 0; i < threadsCount; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// display time after computation
System.out.println("Execution time: " + (System.currentTimeMillis() - time));
}
}
它工作正常,现在我想为 2 或 3 个线程运行它并计算每个线程的计算时间。然后我将比较时间:用t1
和记下它们t2
,如果|t1 - t2| < small epsilon
,我会说我的算法在某些给定条件下以细粒度执行,即线程花费的时间相对相同。
如何测量线程的时间?