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?

Hades
  • 119
  • 8
  • https://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java – meowgoesthedog Oct 23 '18 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. – Selaron Oct 23 '18 at 14:44
  • [How do I write a correct micro-benchmark in Java?](https://stackoverflow.com/q/504103/2711488) – Holger Oct 23 '18 at 14:50

1 Answers1

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?

B. Cratty
  • 1,725
  • 1
  • 17
  • 32
  • This is what I have already mentioned in my question. The thing is not about HOW to do it. – Hades Oct 23 '18 at 14:50
  • 1
    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](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java) I am sorry if this still leaves you unanswered. – B. Cratty Oct 23 '18 at 14:54
  • 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. – B. Cratty Oct 23 '18 at 15:04