I often write preformance test for small code snippets to figure out what the, at least in my eyes, is the best and fasted code.
One example is checking to see if overall NIO file access is faster for my scenerio, instead of non nio based file access. Or how expensive method calls are, compared to direct instance variable access. I have a timertestcase which I use for timing how long a method is running. The problem is that one time something takes 50 ms another time 10 ms and again another time it takes 80 ms (even doing non file based things). So I thought it would be nice to check out the jdk 1.5 System.nanoTime(). I created the test (see below) and to my surprise, nanoTime actually gives better time feedback than System.currentTimeMillis. The testscenario is setting registring the starttime, sleep for 55 ms and registring the stoptime. This should end up with about 55.
I am looping 50 times.
System.currentTimeMillis has 0 hits on 55 ms and minimum was 46 ms and the maximum was 63, although this gives you an average of 54,5.
System.nanoTime() has 49 hits on 55 ms and one miss at 63.
Don't know what to think of this though. Just in case someone is intersted : the test was run on Windows XP sp 2, P4 3.0Ghz, with 1 gig of RAM, and the test was run from eclipse.
Here is the code... Curious about the result of others.. It's not a contest for nice coding practices though :)
long start = 0;
long stop = 0;
int correctMs = 0;
long maxValue = 0;
long minValue = -1;
long total = 0;
for (int i = 0; i < 50; i++) {
start = System.currentTimeMillis();
Thread.sleep(55);
stop = System.currentTimeMillis();
total = stop -start;
if (total == 55) {
correctMs++;
} else {
if (total > maxValue) maxValue = total;
if (total < minValue || minValue == -1) minValue = total;
}
}
System.out.println("Correct ms : " + correctMs);
System.out.println("min : " + minValue);
System.out.println("max : " + maxValue);
int correctNs = 0;
maxValue = 0;
minValue = -1;
for (int i = 0; i < 50; i++) {
start = System.nanoTime();
Thread.sleep(55);
stop = System.nanoTime();
total = ((stop - start) / 1000000);
if (total == 55) {
correctNs++;
} else {
if (total > maxValue) maxValue = total;
if (total < minValue || minValue == -1) minValue = total;
}
}
System.out.println("Correct ms : " + correctNs);
System.out.println("min : " + minValue);
System.out.println("max : " + maxValue);
Update : Sam Pullara gave me a fix for the code (already changed above) and noted that commenting wasn't working, which is fixed again Thanx. Sam.
He also gave me the results from above for the MacOS and there was less difference between the 2 methods than on my machine :
Correct ms : 48
min : 56
max : 56
Correct ms : 47
min : 54
max : 54