Returns a formatted string presenting the average elapsed time based on the passed time stamp and count of incidents in the native nanos, microseconds, milliseconds and seconds. - Java java.sql

Java examples for java.sql:Timestamp

Description

Returns a formatted string presenting the average elapsed time based on the passed time stamp and count of incidents in the native nanos, microseconds, milliseconds and seconds.

Demo Code

//package com.java2s;

import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] argv) {
        String title = "java2s.com";
        long nanos = 123123123;
        long count = 2;
        System.out.println(reportAvgs(title, nanos, count));
    }/*w w w. j  av  a 2s. com*/

    /**
     * Returns a formatted string presenting the average elapsed time 
     * based on the passed time stamp and count of incidents in the native nanos, microseconds, milliseconds and seconds.
     * @param title The arbitrary name for the timing
     * @param nanos The elapsed time in nanos
     * @param count The number of incidents, used for calculating an average
     * @return the formatted message
     */
    public static String reportAvgs(String title, long nanos, long count) {
        if (nanos == 0 || count == 0)
            return reportTimes(title, 0);
        return reportTimes(title, (nanos / count));
    }

    /**
     * Returns a formatted string presenting the passed elapsed time in the native nanos, microseconds, milliseconds and seconds.
     * @param title The arbitrary name for the timing
     * @param nanos The elapsed time in nanos
     * @return the formatted message
     */
    public static String reportTimes(String title, long nanos) {
        StringBuilder b = new StringBuilder(title).append(":  ");
        b.append(nanos).append(" ns.  ");
        b.append(TimeUnit.MICROSECONDS.convert(nanos, TimeUnit.NANOSECONDS))
                .append(" \u00b5s.  ");
        b.append(TimeUnit.MILLISECONDS.convert(nanos, TimeUnit.NANOSECONDS))
                .append(" ms.  ");
        b.append(TimeUnit.SECONDS.convert(nanos, TimeUnit.NANOSECONDS))
                .append(" s.");
        return b.toString();
    }
}

Related Tutorials