这是在Java中为并发线程计时的正确方法吗?

时间:2015-09-23 22:13:44

标签: java multithreading timing cpu-time

我需要花时间运行我编写的应用程序的每个线程需要多长时间,并且我已经完成并得到了结果,但是没有任何好的方法来验证我做得对。我以前从未做过这样的事。如果有人能给我一个快速校对,那将非常有帮助。

以下是创建线程的代码:

for (int i = 0; i < ROWS; i++) {
    threads[threadCount] = new Thread(new TextDistanceThread("Macbeth.txt", "Othello.txt", i, 0));
    threads[threadCount++].start();
    threads[threadCount] = new Thread(new TextDistanceThread("Macbeth.txt", "HuckFinn.txt", i, 1));
    threads[threadCount++].start();
    threads[threadCount] = new Thread(new TextDistanceThread("Macbeth.txt", "TomSawyer.txt", i, 2));
    threads[threadCount++].start();
    threads[threadCount] = new Thread(new TextDistanceThread("Othello.txt", "HuckFinn.txt", i, 3));
    threads[threadCount++].start();
    threads[threadCount] = new Thread(new TextDistanceThread("Othello.txt", "TomSawyer.txt", i, 4));
    threads[threadCount++].start();
    threads[threadCount] = new Thread(new TextDistanceThread("TomSawyer.txt", "HuckFinn.txt", i, 5));
    threads[threadCount++].start();
}

线程本身的代码:

public void run() {

    long start = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();

//DO SOME STUFF

    long end = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();

    Driver.timeResults[0][row][col] = end - start;
    Driver.results[row][col] = difference;
}

2 个答案:

答案 0 :(得分:1)

您要么需要每线程经过的时间,要么需要System.currentTime()的“实际”经过时间;您的代码获取每线程时间,这并不总是与实际经过的时间相同。如果这是你的意图,你的实现应该有效。

验证计时行为的简便方法是在已知的持续时间内运行任务。例如Thread.sleep()。尝试将Thread.sleep()与忙等待(即while(System.currentTimeMillis() < timeInTheFuture) {})进行比较,您会发现CPU时间可能会有所不同。不要期望高精度,但您仍然可以使用它来验证您的假设。如果启动五个线程,每个线程工作30秒,那么每个线程的回复时间是大约30秒吗?然后它正在做你期望的事情。

也就是说,看起来你将时序信息存储在一个数组中,这不是一个好主意。 Arrays are not thread-safe。对于您的情况,最简单的方法是创建一个ConcurrentHashMap<String, Long>,其中键是线程名称,例如。

timeResults.put(Thread.currentThread().getName(), end - start);

答案 1 :(得分:0)

如果你想测量CPU在每个线程上花费的时间,那么你的代码看起来是正确的。请注意,它不会测量从线程启动到完成时的实际时间 - 为此您将使用System.nanoTime()