All Downloads are FREE. Search and download functionalities are using the official Maven repository.

host.anzo.commons.datetime.StopWatch Maven / Gradle / Ivy

There is a newer version: 1.29
Show newest version
package host.anzo.commons.datetime;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.TimeUnit;

/**
 * @author Aristo
 * @since 06.09.2021, 6:25
 */
public class StopWatch {
    private long startTime;
    private long point;
	private long pointTemp;

    public StopWatch() {
        startTime = System.nanoTime();
        point = 0;
    }

    public void pointStart() {
        pointTemp = System.nanoTime();
    }

    public void pointEnd() {
        point += System.nanoTime() - pointTemp;
    }

    public void pointRestart() {
        point = 0;
    }

    public String pointResult() {
        return formatLong(pointResultNanos());
    }

    public String pointResult(long mul) {
        return formatLong(pointResultNanos(mul));
    }

    public long pointResultNanos() {
        return point;
    }

    public long pointResultNanos(long mul) {
        return point / mul;
    }

    public String pointResultAndRestart() {
        long out = pointResultNanos();
        pointRestart();
        return formatLong(out);
    }

    public String pointResultAndRestart(long mul) {
        long out = pointResultNanos(mul);
        pointRestart();
        return formatLong(out);
    }

    public void restart() {
        startTime = System.nanoTime();
    }

    public long result(@NotNull TimeUnit timeUnit) {
        return timeUnit.convert(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
    }

    public String result() {
        return formatLong(result(TimeUnit.NANOSECONDS));
    }

    public String resultAndRestart() {
        final long out = result(TimeUnit.NANOSECONDS);
        restart();
        return formatLong(out);
    }

    private @NotNull String formatLong(long nanos) {
        if (TimeUnit.NANOSECONDS.toSeconds(nanos) > 1) {
            return TimeUnit.NANOSECONDS.toMillis(nanos) / 1000D + " s.";
        }
        else {
            if (TimeUnit.NANOSECONDS.toMillis(nanos) > 1) {
                return TimeUnit.NANOSECONDS.toMicros(nanos) / 1000D + " ms.";
            }
            else {
                return nanos / 1000000D + " ms.";
            }
        }
    }

    @Override
    public String toString() {
        return "Timer: start at " + startTime + "/" + (result()) + " ago. / Point: " + point;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy