Skip to content

Instantly share code, notes, and snippets.

@Cadiboo
Created May 16, 2019 13:04
Show Gist options
  • Save Cadiboo/6aa837692387f65d7e2504180264a88c to your computer and use it in GitHub Desktop.
Save Cadiboo/6aa837692387f65d7e2504180264a88c to your computer and use it in GitHub Desktop.
pls stop crashing
package io.github.cadiboo.nocubes.util;
import net.minecraft.profiler.Profiler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashMap;
/**
* @author Cadiboo
*/
public class ModProfiler extends Profiler implements AutoCloseable {
public static final HashMap<Thread, ModProfiler> PROFILERS = new HashMap<>();
private static final Logger LOGGER = LogManager.getLogger();
private static final ThreadLocal<ModProfiler> PROFILER = ThreadLocal.withInitial(() -> {
final ModProfiler profiler = new ModProfiler();
PROFILERS.put(Thread.currentThread(), profiler);
return profiler;
});
public static boolean profilersEnabled = false;
private int sections = 0;
public ModProfiler() {
if (profilersEnabled) {
this.startProfiling(0);
}
}
public static void enableProfiling() {
profilersEnabled = true;
synchronized (PROFILERS) {
for (final ModProfiler profiler : PROFILERS.values()) {
profiler.startProfiling(0);
}
}
}
public static void disableProfiling() {
profilersEnabled = false;
synchronized (PROFILERS) {
for (final ModProfiler profiler : PROFILERS.values()) {
profiler.stopProfiling();
}
}
}
public static ModProfiler get() {
return PROFILER.get();
}
public ModProfiler start(final String name) {
if (!profilersEnabled) {
return this;
}
++sections;
startSection(name);
// return this to allow use in try-with-resources blocks
return this;
}
public void end() {
if (!profilersEnabled) {
while (sections > 0) {
--sections;
endSection();
}
}
if (sections > 0) {
--sections;
endSection();
}
}
@Override
public void close() {
end();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment