5

I want to run a stop watch form the beginning of my program

and log the time split of some intervals.

Which StopWatch should I prefer?

import com.google.common.base.Stopwatch;

org.apache.commons.lang.time.StopWatch

For example:

Start -----> split 1 (1:00 min from split 0) ----> split 2 (0:30 from split 1) -->  split 3 (0:35 from split 2)

and not

Start -----> split 1 (1:00 min from start) ----> split 2 (1:30 from from start) ----> split 3 (2:05 from from start) 

Is there a more elegant way to do so than this?

stopWatch.split();
stopWatch.getSplitTime() - lastSpiltTime;
last splitTime = stopWatch.getSplitTime();
xxks-kkk
  • 2,336
  • 3
  • 28
  • 48
Elad Benda
  • 35,076
  • 87
  • 265
  • 471

2 Answers2

2

Unfortunately, this is the only way. I had the same need, but Apache StopWatch does not have native support for this.

I did it a slightly different way:

private void lapWatchAndLog( StopWatch watch, String messageForLap ) {

    watch.stop();
    LOGGER.info( String.format( "Time: [%s] %s", watch.getTime(), messageForLap ) );
    watch.reset();
    watch.start();
}
Dan Torrey
  • 1,379
  • 15
  • 25
1

Or you can use this:

private long stopWatchGap(StopWatch stopWatch) {
    try {
        stopWatch.stop();
        return stopWatch.getTime();
    } finally {
        stopWatch.reset();
        stopWatch.start();
    }
}

just to return gap value.

Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
puppylpg
  • 909
  • 10
  • 23