0

I need to know how long my algorithm`s implementation is executed. What I do:

long m1 = System.currentTimeMillis();
        bm.search(mediumtext, mediumpattern);
        System.out.println(System.currentTimeMillis() - m1);

But with every new run for the same example, it shows different values. So far I got them in the range 23 to 29.

I tried also

long mediumtime = System.nanoTime();
bm.search(mediumtext, mediumpattern);
mediumtime = System.nanoTime() - mediumtime;
System.out.printf("Elapsed %,9.3f ms\n", mediumtime/1_000_000.0);

And the problem is the same. Why it shows totally different values for the same example?

Maybe there is a more exact and correct way to get execution time?

  • 1
    Definitely read up on the above on how to do micro benchmarking. You'll never get exact execution times but if you don't take that advice into account (and your question doesn't), your results are meaningless - you're mostly measuring how long it takes the JVM to load and initialise classes, profile your code, compile it to native code, etc – Erwin Bolwidt Nov 28 '20 at 21:43

2 Answers2

0

When you are running your code, you are not the only thing occupying the CPU/Processor + Memory + I/O. Those 3 affect the Java Runtime Environment and how fast/quick it executes a given command.

Therefore you getting between 23-29 is how long it takes to run, and that is perfectly acceptable.

This is all based on my understanding of your question. There is no way to always get 23, 23, 23, 23, 23

JCompetence
  • 6,997
  • 3
  • 19
  • 26
0

I don't know if it would help but in my projects i have used this :

long start = System.currentTimeMillis();
bm.search(mediumtext, mediumpattern);
long elapsedTimeMillis = System.currentTimeMillis() - start;
float min = elapsedTimeMillis / (60 * 1000F);
min = (float) Math.floor(min * 100) / 100;
System.out.println("Task performed in " + min + " minutes");

Matteo
  • 120
  • 10