1

Is there a way to precisely measure execution time of an algorithm written in Java? My task is to design an algorithm solving TSP, with recommend language used being C++. However, if I want to write it in Java, I have to prove that the measured time is in fact algorithm execution time, and not time taken by any operations JVM might perform whilst running the algorithm.

Using System.nanoTime() right before and after executing the algorithm should be enough, or can I do something more?

3
  • stackoverflow.com/questions/180158/… Commented Oct 23, 2018 at 14:36
  • 2
    Beside what @meowgoesthedog pointed at, there are several aspects influencing algorithm performance. Massive Object instantiation with 'new' operator may slow down your algorithm. Use primitives and re-use Objects where possible. When running the algo multiple times within same JVM, it might speed up due to JIT compiler optimizations. And the garbage collector may hit the CPU. If you dont create too many Objects, give the new noop Garbage collector a chance. Commented Oct 23, 2018 at 14:44
  • How do I write a correct micro-benchmark in Java? Commented Oct 23, 2018 at 14:50

1 Answer 1

1

Simple Approach:

The quickest and easiest way to do this would be by using the following:

long startTime = System.nanoTime();
Algorithm();
long endTime = System.nanoTime();

long duration = (endTime - startTime);  //divide by 1000000 to get milliseconds.

If you are looking for different ways to this refer here, How do I time a method's execution in Java?

Micro-Benchmark Approach:

Use the following link to get guidlines on how to properly make a micro-benchmark in Java & JVM: How do I write a correct micro-benchmark in Java?

Sign up to request clarification or add additional context in comments.

3 Comments

This is what I have already mentioned in my question. The thing is not about HOW to do it.
I understand, my answer was to make it known that from what I was able to gather up the best way to achieve what you were looking for was using nanoTime(). So the answer to your question is there is not much more you can do. One link I have seen so far that could help you try to optimize this process was the one that @Holger used which was How to write Micro-Benchmark in Java I am sorry if this still leaves you unanswered.
Youre welcome, I will edit my answer to supply that link as well to make it easier next time you or someone else comes back to this post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.