开发者

Getting Execution time in Multithreaded program

开发者 https://www.devze.com 2023-01-25 04:33 出处:网络
I am trying to sort an array using multithreading in java and note its execution time. I am using System.nanoTime() for the same.

I am trying to sort an array using multithreading in java and note its execution time. I am using System.nanoTime() for the same.

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 re开发者_JAVA技巧sults given that I did not put main.sleep() ?? or is it handled by the 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() ?? or is it handled by the JVM .

The System.nanoTime() is supposed to give you the best (most precise) available measure of elapsed time. Note:

  • this is NOT a measure of the CPU time used, and
  • 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.

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.

( EDIT - If you want to find out how much CPU time was used by each thread, take a look the 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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消