Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 267
src/client/java/com/kodari/framescope/FrameScopeClient.java
package com.kodari.framescope;
import com.sun.management.OperatingSystemMXBean;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientChunkEvents;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.rendering.v1.level.LevelRenderEvents;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.management.ManagementFactory;
import java.util.Locale;
public final class FrameScopeClient implements ClientModInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger("framescope");
private static SessionMetrics activeSession;
@Override
public void onInitializeClient() {
ClientTickEvents.END_CLIENT_TICK.register(client -> {
long now = System.nanoTime();
if (client.level == null) {
finishSession(now);
return;
}
if (activeSession == null) {
activeSession = new SessionMetrics(now);
}
activeSession.sampleRuntime(now);
});
LevelRenderEvents.END_MAIN.register(context -> {
SessionMetrics session = activeSession;
if (session != null) {
session.recordFrame(System.nanoTime());
}
});
ClientChunkEvents.CHUNK_LOAD.register((level, chunk) -> {
SessionMetrics session = activeSession;
if (session != null) {
session.recordChunkLoad();
}
});
LOGGER.info("FrameScope is recording client world-session metrics; a summary is logged after leaving a world.");
}
private static void finishSession(long now) {
SessionMetrics session = activeSession;
if (session != null) {
activeSession = null;
LOGGER.info(session.formatSummary(now));
}
}
private static final class SessionMetrics {
private static final long NANOS_PER_MILLI = 1_000_000L;
private static final long NANOS_PER_SECOND = 1_000_000_000L;
private static final int FRAME_TIME_HISTOGRAM_LIMIT_MS = 1_500;
private final long startedAtNanos;
private final long startingHeapBytes;
private final long[] frameTimeHistogram = new long[FRAME_TIME_HISTOGRAM_LIMIT_MS];
private final OperatingSystemMXBean operatingSystemBean = getOperatingSystemBean();
private long lastFrameNanos;
private long firstFrameNanos;
private long frameCount;
private double meanFrameNanos;
private double frameTimeM2;
private long overflowFrameCount;
private double overflowFrameNanos;
private long maximumFrameNanos;
private long chunkLoadCount;
private long peakHeapBytes;
private long lastCpuSampleNanos;
private long cpuSampleCount;
private double cpuLoadTotal;
private double maximumCpuLoad;
private SessionMetrics(long startedAtNanos) {
this.startedAtNanos = startedAtNanos;
this.lastCpuSampleNanos = startedAtNanos;
this.startingHeapBytes = usedHeapBytes();
this.peakHeapBytes = startingHeapBytes;
}
private void recordFrame(long now) {
if (firstFrameNanos == 0) {
firstFrameNanos = now;
}
if (lastFrameNanos != 0) {
long frameNanos = now - lastFrameNanos;
frameCount++;
double delta = frameNanos - meanFrameNanos;
meanFrameNanos += delta / frameCount;
frameTimeM2 += delta * (frameNanos - meanFrameNanos);
maximumFrameNanos = Math.max(maximumFrameNanos, frameNanos);
long frameMillis = frameNanos / NANOS_PER_MILLI;
if (frameMillis >= FRAME_TIME_HISTOGRAM_LIMIT_MS) {
overflowFrameCount++;
overflowFrameNanos += frameNanos;
} else {
frameTimeHistogram[(int) frameMillis]++;
}
}
lastFrameNanos = now;
}
private void recordChunkLoad() {
chunkLoadCount++;
}
private void sampleRuntime(long now) {
long heapBytes = usedHeapBytes();
peakHeapBytes = Math.max(peakHeapBytes, heapBytes);
if (now - lastCpuSampleNanos >= NANOS_PER_SECOND) {
lastCpuSampleNanos = now;
if (operatingSystemBean != null) {
double load = operatingSystemBean.getProcessCpuLoad();
if (load >= 0.0 && Double.isFinite(load)) {
cpuSampleCount++;
cpuLoadTotal += load;
maximumCpuLoad = Math.max(maximumCpuLoad, load);
}
}
}
}
private String formatSummary(long endedAtNanos) {
double durationSeconds = (endedAtNanos - startedAtNanos) / (double) NANOS_PER_SECOND;
double averageFrameMs = frameCount == 0 ? 0.0 : meanFrameNanos / NANOS_PER_MILLI;
double averageFps = averageFrameMs == 0.0 ? 0.0 : 1_000.0 / averageFrameMs;
double onePercentLowFps = frameCount == 0 ? 0.0 : 1_000.0 / slowestOnePercentAverageMs();
double frameTimeStdDevMs = frameCount < 2 ? 0.0 : Math.sqrt(frameTimeM2 / (frameCount - 1)) / NANOS_PER_MILLI;
double p99FrameMs = frameCount == 0 ? 0.0 : percentileFrameTimeMs(0.99);
double firstFrameSeconds = firstFrameNanos == 0 ? Double.NaN : (firstFrameNanos - startedAtNanos) / (double) NANOS_PER_SECOND;
double chunkRate = durationSeconds <= 0.0 ? 0.0 : chunkLoadCount / durationSeconds;
double averageCpuPercent = cpuSampleCount == 0 ? Double.NaN : cpuLoadTotal * 100.0 / cpuSampleCount;
double maximumCpuPercent = cpuSampleCount == 0 ? Double.NaN : maximumCpuLoad * 100.0;
long endingHeapBytes = usedHeapBytes();
peakHeapBytes = Math.max(peakHeapBytes, endingHeapBytes);
return String.format(Locale.ROOT,
"FrameScope world-session metrics: duration=%.1fs, time-to-first-world-frame=%.2fs, frames=%d, average=%.1f FPS, 1%% low=%.1f FPS, p99-frame=%.2fms, frame-time-stddev=%.2fms, max-frame=%.2fms, process-CPU-average=%.1f%%, process-CPU-peak=%.1f%%, heap-start/peak/end=%.1f/%.1f/%.1f MiB, chunks-loaded=%d (%.2f/s)",
durationSeconds, firstFrameSeconds, frameCount, averageFps, onePercentLowFps, p99FrameMs,
frameTimeStdDevMs, maximumFrameNanos / (double) NANOS_PER_MILLI,
averageCpuPercent, maximumCpuPercent, toMebibytes(startingHeapBytes),
toMebibytes(peakHeapBytes), toMebibytes(endingHeapBytes), chunkLoadCount, chunkRate);
}
private double percentileFrameTimeMs(double percentile) {
long target = Math.max(1, (long) Math.ceil(frameCount * percentile));
long seen = 0;
for (int bucket = 0; bucket < frameTimeHistogram.length; bucket++) {
seen += frameTimeHistogram[bucket];
if (seen >= target) {
return bucket + 0.5;
}
}
return overflowFrameCount == 0 ? 0.0 : overflowFrameNanos / overflowFrameCount / NANOS_PER_MILLI;
}
private double slowestOnePercentAverageMs() {
long remaining = Math.max(1, (long) Math.ceil(frameCount * 0.01));
double frameTimeTotalMs = 0.0;
if (overflowFrameCount > 0) {
long take = Math.min(remaining, overflowFrameCount);
frameTimeTotalMs += take * overflowFrameNanos / overflowFrameCount / NANOS_PER_MILLI;
remaining -= take;
}
for (int bucket = frameTimeHistogram.length - 1; bucket >= 0 && remaining > 0; bucket--) {
long take = Math.min(remaining, frameTimeHistogram[bucket]);
frameTimeTotalMs += take * (bucket + 0.5);
remaining -= take;
}
return remaining > 0 ? 0.0 : frameTimeTotalMs / Math.max(1, (long) Math.ceil(frameCount * 0.01));
}
private static OperatingSystemMXBean getOperatingSystemBean() {
java.lang.management.OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
return bean instanceof OperatingSystemMXBean operatingSystemMXBean ? operatingSystemMXBean : null;
}
private static long usedHeapBytes() {
Runtime runtime = Runtime.getRuntime();
return runtime.totalMemory() - runtime.freeMemory();
}
private static double toMebibytes(long bytes) {
return bytes / (1024.0 * 1024.0);
}
}
}