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 results 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??
The
System.nanoTime()is supposed to give you the best (most precise) available measure of elapsed time. Note: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
ThreadMXBeanAPI.)That is far too general a question to answer, except to say “probably yes” … or “profile it”.