简体   繁体   English

在多线程程序中获取执行时间

[英]Getting Execution time in Multithreaded program

I am trying to sort an array using multithreading in java and note its execution time. 我正在尝试使用Java中的多线程对数组进行排序,并注意其执行时间。 I am using System.nanoTime() for the same. 我使用System.nanoTime()相同。

Here is a template of the code 这是代码的模板

start = System.nanoTime();
sort();   // calls different threads to completely sort the array
end = System.nanoTime()

What I want to ask is that the above is in main Thread so will it give me incorrect time results given that I did not put main.sleep() ?? 我想问的是上面的内容在main Thread中,因此如果我没有放置main.sleep(),它将给我不正确的时间结果吗? or is it handled by the JVM . 还是由JVM处理。 Also if I am in need of fast execution is there something that can improve the performance of above code in terms of time execution?? 另外,如果我需要快速执行,有什么可以在时间执行方面提高上述代码的性能的?

What I want to ask is that the above is in main Thread so will it give me incorrect time results given that I did not put main.sleep() ?? 我想问的是上面的内容在main Thread中,因此如果我没有放置main.sleep(),它将给我不正确的时间结果吗? or is it handled by the JVM . 还是由JVM处理。

The System.nanoTime() is supposed to give you the best (most precise) available measure of elapsed time. System.nanoTime()应该为您提供最佳(最精确)的经过时间度量。 Note: 注意:

  • this is NOT a measure of the CPU time used, and 这不能衡量所使用的CPU时间,并且
  • on some versions of Java / OS platforms, System.nanoTime() uses a hardware clock that is not synchronized across different cores, and (apparently) can be rather inaccurate as a result. 在某些版本的Java / OS平台上, System.nanoTime()使用的硬件时钟在不同内核之间不同步,因此(显然)可能不准确。

Personally, I'd use System.currentTimeMillis() , and make sure that I benchmarked the sorting of a large array or collection ... and did various other things to make sure that my benchmark was valid. 就个人而言,我将使用System.currentTimeMillis() ,并确保对大型数组或集合的排序进行基准测试……并进行其他各种操作以确保基准测试有效。

( EDIT - If you want to find out how much CPU time was used by each thread, take a look the ThreadMXBean API.) 编辑 -如果您想找出每个线程使用了多少CPU时间,请看一下ThreadMXBean API。)

Also if I am in need of fast execution is there something that can improve the performance of above code in terms of time execution?? 另外,如果我需要快速执行,有什么可以在时间执行方面提高上述代码的性能的?

That is far too general a question to answer, except to say "probably yes" ... or "profile it". 除了说“可能是”……或“描述它”之外,这是一个过于笼统的问题。

You can use the JVisualVM profiler (or another profiler) to find how fast each of your methods executes. 您可以使用JVisualVM事件探查器(或另一个事件探查器)来查找每个方法的执行速度。

All you need is a pause at the beginning to allow you to attach it, and a pause at the end so you can view and/or save the results. 您需要做的只是在开头添加一个暂停以允许您附加它,并在结尾添加一个暂停,以便您可以查看和/或保存结果。

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

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