1

I’m recently working with guava. Stopwatch has such a question. I have a method that calculates the total time the put method is executed and the quantity, in order to calculate the average time spent on the execution of the put method.

        Stopwatch stopwatch = Stopwatch.createStarted();
        cacheEntry.put(str, new CacheEntry(str));
        putCounter++;
        mapBasedStatisticsCache.setPutCounter(putCounter);
        currentTime += stopwatch.stop().elapsed(TimeUnit.NANOSECONDS);
        System.out.println(currentTime);
        mapBasedStatisticsCache.setCurrentTime(currentTime);

After that, I calculate the average time in nanoseconds

public long getAveragePutTime() {
        return getCurrentTime() / getPutCounter();
    }

How can I then parse the result of the getAveragePutTime method to the hh: mm: ss: ms format?

I'm trying to do this way:

public String getAveragePutTime() {
    long result = getCurrentTime() / getPutCounter();
    long hh = TimeUnit.NANOSECONDS.toHours(result);
    long mm = TimeUnit.NANOSECONDS.toMinutes(result);
    long ss = TimeUnit.NANOSECONDS.toSeconds(result);
    long ms = TimeUnit.NANOSECONDS.toMillis(result);
    return "Hours: " + hh + " minutes: " + mm + " seconds: " + ss + " millisecond: " + ms;
}

But I have this result:

Nanos: 128240
Hours: 0 minutes: 0 seconds: 0 millisecond: 0
Mefisto_Fell
  • 876
  • 1
  • 10
  • 30

1 Answers1

0

You have 128420 nanoseconds. That's 0.000128420 seconds. That's 0.128420 milliseconds. 0.128420 milliseconds in integers is 0 milliseconds. So your result is actually normal.

However... You have other issues! Your getAveragePutTime() is written in a way that you will have redundant numbers. So when you have hours, remove them from the leftovers:

public String getAveragePutTime() {
  long result = getCurrentTime() / getPutCounter();
  long hh = TimeUnit.NANOSECONDS.toHours(result);
  result -= TimeUnit.HOURS.toNanos(hh);
  long mm = TimeUnit.NANOSECONDS.toMinutes(result);
  result -= TimeUnit.MINUTES.toNanos(mm);
  long ss = TimeUnit.NANOSECONDS.toSeconds(result);
  result -= TimeUnit.SECONDS.toNanos(mm);
  long ms = TimeUnit.NANOSECONDS.toMillis(result);
  return "Hours: " + hh + " minutes: " + mm + " seconds: " + ss + " millisecond: " + ms;
}
Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137