planetiler/planetiler-core/src/main/java/com/onthegomap/planetiler/stats/ProcessTime.java

53 wiersze
1.6 KiB
Java
Czysty Zwykły widok Historia

package com.onthegomap.planetiler.stats;
2021-06-04 11:22:40 +00:00
import com.onthegomap.planetiler.util.Format;
2021-06-04 11:22:40 +00:00
import java.time.Duration;
2022-01-28 01:23:24 +00:00
import java.util.Locale;
2021-06-04 11:22:40 +00:00
import java.util.Optional;
2021-09-10 00:46:20 +00:00
/**
* A utility for measuring the wall and CPU time that this JVM consumes between snapshots.
* <p>
* For example:
*
* <pre>
* {@code
2021-09-10 00:46:20 +00:00
* var start = ProcessTime.now();
* // do expensive work...
* var end - ProcessTime.now();
* LOGGER.log("Expensive work took " + end.minus(start));
* }
* </pre>
2021-09-10 00:46:20 +00:00
*/
public record ProcessTime(Duration wall, Optional<Duration> cpu, Duration gc) {
2021-06-04 11:22:40 +00:00
2021-09-10 00:46:20 +00:00
/** Takes a snapshot of current wall and CPU time of this JVM. */
2021-06-04 11:22:40 +00:00
public static ProcessTime now() {
return new ProcessTime(Duration.ofNanos(System.nanoTime()), ProcessInfo.getProcessCpuTime(),
ProcessInfo.getGcTime());
2021-06-04 11:22:40 +00:00
}
2021-09-10 00:46:20 +00:00
/** Returns the amount of time elapsed between {@code other} and {@code this}. */
2021-06-04 11:22:40 +00:00
ProcessTime minus(ProcessTime other) {
return new ProcessTime(
wall.minus(other.wall),
cpu.flatMap(thisCpu -> other.cpu.map(thisCpu::minus)),
gc.minus(other.gc)
);
2021-06-04 11:22:40 +00:00
}
2022-01-28 01:23:24 +00:00
public String toString(Locale locale) {
Format format = Format.forLocale(locale);
Optional<String> deltaCpu = cpu.map(format::duration);
2022-01-28 01:23:24 +00:00
String avgCpus = cpu.map(cpuTime -> " avg:" + format.decimal(cpuTime.toNanos() * 1d / wall.toNanos()))
.orElse("");
String gcString = gc.compareTo(Duration.ofSeconds(1)) > 0 ? (" gc:" + format.duration(gc)) : "";
return format.duration(wall) + " cpu:" + deltaCpu.orElse("-") + gcString + avgCpus;
2022-01-28 01:23:24 +00:00
}
2021-06-04 11:22:40 +00:00
@Override
public String toString() {
2022-01-28 01:23:24 +00:00
return toString(Format.DEFAULT_LOCALE);
2021-06-04 11:22:40 +00:00
}
}