繁体   English   中英

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

[英]Is this the proper way to time concurrent threads in Java

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

这是创建线程的代码:

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;
}

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM