-1

Im C++ coder but somehow today I ended with Java, so I did little project with some sorting algorithms (I made them into classes) and I wonder, is it possible to println passed time of calculation of a class ? Not whole project but only one class ? So I can compare theese algorithms.

Thank you for any help.

Miki
  • 15
  • 1
  • 4
  • 1
    You can use `System.currentTimeMillis()` to get the current time in milliseconds since epoch. – devgianlu Feb 27 '19 at 18:16
  • 1
    @devgianlu Better to use [`System.nanoTime()`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime--), for more precision, when calculating *elapsed* time. – Andreas Feb 27 '19 at 18:17
  • And for the record: you are supposed to do serious research prior posting questions. An experience coder could know how to first use a search engine ... to find answer in way less time than required to put a question here. – GhostCat Feb 27 '19 at 18:19
  • One executes a merthod, not a class., That being said, the simple solution is System.nanoTime(). For the correct solution, look up Java Microbenchmark. One of teh first things that pop up is https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java –  Feb 27 '19 at 18:19

1 Answers1

1

You can get the current time at the beginning and at the end of the code, and subtract them:

long s = System.nanoTime();

//Your code;

long elapsed = System.nanoTime() - s;

Your time elapsed will be in nanoseconds, but it's an easy conversion.

Ayrton
  • 2,218
  • 1
  • 14
  • 25