Roma Kap Roma Kap - 10 days ago 6
Java Question

Collection Test with StopWatch

I'm trying to measure the elapsed time of a collection with 115 items.
My problem is that I can measure the elapsed time only when I am debuging and exactly set a breakpoint by using

StopWatch.stop();

When i run my test normal the value of
StopWatch.stop
is
0
, although it is a long-value. First I thought that my collection is to small, but this elapsed time should be passed as long-value.

// times-collection will be initialised somewhere else
//---------------------------------------------------------------
for (int i=0; i<10; i++){
final StopWatch stopwatchA = new StopWatch();
final StopWatch stopwatchB = new StopWatch();
Iterator<String> iterator = times.iterator();

stopwatchA.start();
while(iterator.hasNext()){
if (iterator.next().equals("XXX")) {
break;
}
}
stopwatchA.stop();
stopwatchB.start();
for (String tzd : times) {

if (tzd.equals("XXX")) {
break;
}
}
stopwatchB.stop();

if(stopwatchA.getTime() < stopwatchB.getTime()){
System.out.println("ITERATOR IS FASTER: iterator: " + estimatedTimeIterator + " FOR-TIME: " + estimatedTimeFor);
}else if(stopwatchA.getTime() > stopwatchB.getTime()){
System.out.println("FOR IS FASTER: iterator: " + estimatedTimeIterator + " FOR-TIME: " + estimatedTimeFor);
}
}

Answer

Stopwatch from Standard Libraries uses internally System.currentTimeMillis() For a collection with 115 items it is perfectly possible to have less than 1ms between stopwatchA.start() and stopwatchA.stop() Use System.nanoTime() instead.