fix stack size assumption at profiler start

This commit is contained in:
dfsek 2021-04-12 09:19:03 -07:00
parent 339413c0de
commit bd3136ca92
2 changed files with 20 additions and 5 deletions

View File

@ -1,5 +1,6 @@
package com.dfsek.terra.profiler;
import com.dfsek.terra.api.util.mutable.MutableInteger;
import com.dfsek.terra.profiler.exception.MalformedStackException;
import java.util.ArrayList;
@ -15,6 +16,8 @@ public class ProfilerImpl implements Profiler {
private volatile boolean running = false;
private static boolean instantiated = false;
private static final ThreadLocal<Boolean> SAFE = ThreadLocal.withInitial(() -> false);
private static final ThreadLocal<MutableInteger> STACK_SIZE = ThreadLocal.withInitial(() -> new MutableInteger(0));
public ProfilerImpl() {
if(instantiated) throw new IllegalStateException("Only one instance of Profiler may exist!");
@ -23,15 +26,18 @@ public class ProfilerImpl implements Profiler {
@Override
public void push(String frame) {
if(running) {
STACK_SIZE.get().increment();
if(running && SAFE.get()) {
Stack<Frame> stack = THREAD_STACK.get();
stack.push(new Frame(stack.size() == 0 ? frame : stack.peek().getId() + "." + frame));
}
stack.push(new Frame(stack.isEmpty() ? frame : stack.peek().getId() + "." + frame));
} else SAFE.set(false);
}
@Override
public void pop(String frame) {
if(running) {
MutableInteger size = STACK_SIZE.get();
size.decrement();
if(running && SAFE.get()) {
long time = System.nanoTime();
Stack<Frame> stack = THREAD_STACK.get();
@ -51,6 +57,7 @@ public class ProfilerImpl implements Profiler {
timings.add(time - top.getStart());
}
if(size.get() == 0) SAFE.set(true);
}
@Override

View File

@ -7,7 +7,7 @@ public class ProfilerTest {
private static final Profiler PROFILER = new ProfilerImpl();
//@Test
public static void main(String... a) throws InterruptedException {
PROFILER.start();
//PROFILER.start();
for(int i = 0; i < 1000; i++) {
doThing();
}
@ -20,6 +20,14 @@ public class ProfilerTest {
doOtherThing();
}
PROFILER.stop();
PROFILER.push("thing");
PROFILER.push("thing2");
PROFILER.start();
PROFILER.pop("thing2");
PROFILER.pop("thing");
PROFILER.push("thing4");
PROFILER.pop("thing4");
PROFILER.getTimings().forEach((id, timings) -> {
System.out.println(id + ": " + timings.toString());
});