Zzz...
Zzz...

Reputation: 291

calculate the runtime for the Java program

I want to calculate the runtime of my Java program. when I used the following method:

long startTime = System.currentTimeMillis();
           ...my program...
long endTime   = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(totalTime); 

the result is different from time to time, so I am thinking to get some (100 or some..) samples and calculate the average to make it more accurate:

long total = 0    
for (int i = 0; i < 100; i++) {
    Long s = System.currentTimeMillis();
    ...my program...
    Long e = System.currentTimeMillis();
    total += (e - s);
}

so I got the total runtime.. for the first method, it is normally about 600ms and for the second method, the result would be around 30000ms (so avg time: 30000/100 = 300ms).

I think it might be related to JVM, it requires some time to load the file or convert it to byte code. and the second method only load&convert once and just run the method 100 times?

I'm not sure about my explanation, please correct me if I'm wrong.

and my problem is: if I want to get the "real" total running time and calculate the average value, what should I do?

Thanks in advance!

Upvotes: 4

Views: 841

Answers (2)

A_Sakir
A_Sakir

Reputation: 23

Netbeans has a Profiler option to calculate runtime of Java applications under Profile section. You might be searching for that since, Profiler calculates actual CPU and memory times. Based on my experiences, I can say it's pretty stable.

Upvotes: 0

Ideasthete
Ideasthete

Reputation: 1541

Timing in Java is bound to be quite unreliable in this fashion, because not only are you going to be sensitive to events happening outside your program, but the nature of JIT compilation and so forth makes it difficult to predict whether or not a given event will take the same amount of time in all situations. Basically, the best you can do is do a TON of iterations and get an average value. Back when I had to do timings for class, I would get pretty consistent timing results if I used tens of thousands of iterations per test, but again, you are not going to get terribly accurate timing in this fashion with Java (and to a lesser extent, any language).

EDIT: Also, you should look into profilers if you desire more accurate timing calculations, as they would probably give a clearer look of execution time per method than trying to do things this way.

Upvotes: 1

Related Questions