From a29029e7cd918a11810e88488610b120db31bbca Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 17 Aug 2017 11:21:43 +0100 Subject: [PATCH] Add profiler for reviewing Mixin performance --- .../asm/mixin/MixinEnvironment.java | 29 +- .../asm/mixin/transformer/ClassInfo.java | 67 +- .../asm/mixin/transformer/MethodMapper.java | 8 +- .../transformer/MixinApplicatorStandard.java | 9 + .../asm/mixin/transformer/MixinInfo.java | 25 +- .../MixinPreProcessorStandard.java | 70 +- .../mixin/transformer/MixinTransformer.java | 161 +++- .../asm/mixin/transformer/TreeInfo.java | 22 +- .../org/spongepowered/asm/util/Counter.java | 47 ++ .../spongepowered/asm/util/perf/Profiler.java | 718 ++++++++++++++++++ 10 files changed, 1081 insertions(+), 75 deletions(-) create mode 100644 src/main/java/org/spongepowered/asm/util/Counter.java create mode 100644 src/main/java/org/spongepowered/asm/util/perf/Profiler.java diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java index 75312045..5e1cc393 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java +++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java @@ -56,6 +56,7 @@ import org.spongepowered.asm.obfuscation.RemapperChain; import org.spongepowered.asm.util.ITokenProvider; import org.spongepowered.asm.util.JavaVersion; import org.spongepowered.asm.util.PrettyPrinter; +import org.spongepowered.asm.util.perf.Profiler; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; @@ -320,6 +321,12 @@ public final class MixinEnvironment implements ITokenProvider { * Enable strict checking for mixin targets */ DEBUG_TARGETS(Option.DEBUG_STRICT, "targets"), + + /** + * Enable the performance profiler for all mixin operations (normally it + * is only enabled during mixin prepare operations) + */ + DEBUG_PROFILER(Option.DEBUG_ALL, Inherit.ALLOW_OVERRIDE, "profiler"), /** * Dumps the bytecode for the target class to disk when mixin @@ -857,6 +864,11 @@ public final class MixinEnvironment implements ITokenProvider { * Logger */ private static final Logger logger = LogManager.getLogger("mixin"); + + /** + * Performance profiler + */ + private static final Profiler profiler = new Profiler(); /** * The phase for this environment @@ -947,9 +959,10 @@ public final class MixinEnvironment implements ITokenProvider { String codeSource = this.getCodeSource(); MixinEnvironment.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Env={}", version, codeSource, side); - if (this.getOption(Option.DEBUG_VERBOSE)) { + boolean verbose = this.getOption(Option.DEBUG_VERBOSE); + if (verbose || this.getOption(Option.DEBUG_EXPORT) || this.getOption(Option.DEBUG_PROFILER)) { PrettyPrinter printer = new PrettyPrinter(32); - printer.add("SpongePowered MIXIN (Verbose debugging enabled)").centre().hr(); + printer.add("SpongePowered MIXIN%s", verbose ? " (Verbose debugging enabled)" : "").centre().hr(); printer.kv("Code source", codeSource); printer.kv("Internal Version", version); printer.kv("Java 8 Supported", CompatibilityLevel.JAVA_8.isSupported()).hr(); @@ -1359,7 +1372,8 @@ public final class MixinEnvironment implements ITokenProvider { public static void init(Phase phase) { if (MixinEnvironment.currentPhase == Phase.NOT_INITIALISED) { MixinEnvironment.currentPhase = phase; - MixinEnvironment.getEnvironment(phase); + MixinEnvironment env = MixinEnvironment.getEnvironment(phase); + MixinEnvironment.getProfiler().setActive(env.getOption(Option.DEBUG_PROFILER)); @SuppressWarnings("unused") MixinLogger logSpy = new MixinLogger(); @@ -1432,6 +1446,15 @@ public final class MixinEnvironment implements ITokenProvider { } } + /** + * Get the performance profiler + * + * @return profiler + */ + public static Profiler getProfiler() { + return MixinEnvironment.profiler; + } + /** * Internal callback * diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java index 3a84ca31..38f94207 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java @@ -54,6 +54,8 @@ import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.ClassSignature; +import org.spongepowered.asm.util.perf.Profiler; +import org.spongepowered.asm.util.perf.Profiler.Section; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -576,6 +578,8 @@ public final class ClassInfo extends TreeInfo { } private static final Logger logger = LogManager.getLogger("mixin"); + + private static final Profiler profiler = MixinEnvironment.getProfiler(); private static final String JAVA_LANG_OBJECT = "java/lang/Object"; @@ -711,44 +715,49 @@ public final class ClassInfo extends TreeInfo { * @param classNode Class node to inspect */ private ClassInfo(ClassNode classNode) { - this.name = classNode.name; - this.superName = classNode.superName != null ? classNode.superName : ClassInfo.JAVA_LANG_OBJECT; - this.methods = new HashSet(); - this.fields = new HashSet(); - this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0); - this.interfaces = new HashSet(); - this.access = classNode.access; - this.isMixin = classNode instanceof MixinClassNode; - this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null; + Section timer = ClassInfo.profiler.begin(Profiler.ROOT, "class.meta"); + try { + this.name = classNode.name; + this.superName = classNode.superName != null ? classNode.superName : ClassInfo.JAVA_LANG_OBJECT; + this.methods = new HashSet(); + this.fields = new HashSet(); + this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0); + this.interfaces = new HashSet(); + this.access = classNode.access; + this.isMixin = classNode instanceof MixinClassNode; + this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null; - this.interfaces.addAll(classNode.interfaces); + this.interfaces.addAll(classNode.interfaces); - for (MethodNode method : classNode.methods) { - this.addMethod(method, this.isMixin); - } + for (MethodNode method : classNode.methods) { + this.addMethod(method, this.isMixin); + } - boolean isProbablyStatic = true; - String outerName = classNode.outerClass; - for (FieldNode field : classNode.fields) { - if ((field.access & Opcodes.ACC_SYNTHETIC) != 0) { - if (field.name.startsWith("this$")) { - isProbablyStatic = false; - if (outerName == null) { - outerName = field.desc; - if (outerName != null && outerName.startsWith("L")) { - outerName = outerName.substring(1, outerName.length() - 1); + boolean isProbablyStatic = true; + String outerName = classNode.outerClass; + for (FieldNode field : classNode.fields) { + if ((field.access & Opcodes.ACC_SYNTHETIC) != 0) { + if (field.name.startsWith("this$")) { + isProbablyStatic = false; + if (outerName == null) { + outerName = field.desc; + if (outerName != null && outerName.startsWith("L")) { + outerName = outerName.substring(1, outerName.length() - 1); + } } } } + + this.fields.add(new Field(field, this.isMixin)); } - this.fields.add(new Field(field, this.isMixin)); + this.isProbablyStatic = isProbablyStatic; + this.outerName = outerName; + this.methodMapper = new MethodMapper(MixinEnvironment.getCurrentEnvironment(), this); + this.signature = ClassSignature.ofLazy(classNode); + } finally { + timer.end(); } - - this.isProbablyStatic = isProbablyStatic; - this.outerName = outerName; - this.methodMapper = new MethodMapper(MixinEnvironment.getCurrentEnvironment(), this); - this.signature = ClassSignature.ofLazy(classNode); } void addInterface(String iface) { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java index da119d6d..0983e6b3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java @@ -36,6 +36,7 @@ import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinMethodNode; +import org.spongepowered.asm.util.Counter; import com.google.common.base.Strings; @@ -43,13 +44,6 @@ import com.google.common.base.Strings; * Maintains method remaps for a target class */ public class MethodMapper { - - /** - * Mutable integer - */ - static class Counter { - public int value; - } /** * Logger diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java index f8c4aac7..6de05e36 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java @@ -64,6 +64,8 @@ import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.ConstraintParser; import org.spongepowered.asm.util.ConstraintParser.Constraint; +import org.spongepowered.asm.util.perf.Profiler; +import org.spongepowered.asm.util.perf.Profiler.Section; import org.spongepowered.asm.util.throwables.ConstraintViolationException; import org.spongepowered.asm.util.throwables.InvalidConstraintException; @@ -230,6 +232,11 @@ class MixinApplicatorStandard { */ protected final ClassNode targetClass; + /** + * Profiler + */ + protected final Profiler profiler = MixinEnvironment.getProfiler(); + MixinApplicatorStandard(TargetClassContext context) { this.context = context; this.targetName = context.getClassName(); @@ -255,9 +262,11 @@ class MixinApplicatorStandard { } for (ApplicatorPass pass : ApplicatorPass.values()) { + Section timer = this.profiler.begin("pass", pass.name().toLowerCase()); for (MixinTargetContext context : mixinContexts) { this.applyMixin(current = context, pass); } + timer.end(); } for (MixinTargetContext context : mixinContexts) { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java index eb33cccc..5d647a0b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -66,6 +66,8 @@ import org.spongepowered.asm.mixin.transformer.throwables.MixinTargetAlreadyLoad import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.launchwrapper.LaunchClassLoaderUtil; +import org.spongepowered.asm.util.perf.Profiler; +import org.spongepowered.asm.util.perf.Profiler.Section; import com.google.common.base.Function; import com.google.common.base.Functions; @@ -677,6 +679,11 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ private final transient Logger logger = LogManager.getLogger("mixin"); + /** + * Profiler + */ + private final transient Profiler profiler = MixinEnvironment.getProfiler(); + /** * Parent configuration which declares this mixin */ @@ -875,7 +882,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { this.logger.error(message); } - if (this.plugin == null || suppressPlugin || this.plugin.shouldApplyMixin(targetName, this.className)) { + if (this.shouldApplyMixin(suppressPlugin, targetName)) { ClassInfo targetInfo = this.getTarget(targetName, checkPublic); if (targetInfo != null && !outTargets.contains(targetInfo)) { outTargets.add(targetInfo); @@ -885,6 +892,13 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { } } + private boolean shouldApplyMixin(boolean suppressPlugin, String targetName) { + Section pluginTimer = this.profiler.begin("plugin"); + boolean result = this.plugin == null || suppressPlugin || this.plugin.shouldApplyMixin(targetName, this.className); + pluginTimer.end(); + return result; + } + private ClassInfo getTarget(String targetName, boolean checkPublic) throws InvalidMixinException { ClassInfo targetInfo = ClassInfo.forName(targetName); if (targetInfo == null) { @@ -1121,7 +1135,10 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ MixinTargetContext createContextFor(TargetClassContext target) { MixinClassNode classNode = this.getClassNode(ClassReader.EXPAND_FRAMES); - return this.type.createPreProcessor(classNode).prepare().createContextFor(target); + Section preTimer = this.profiler.begin("pre"); + MixinTargetContext preProcessor = this.type.createPreProcessor(classNode).prepare().createContextFor(target); + preTimer.end(); + return preProcessor; } /** @@ -1179,7 +1196,9 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ public void preApply(String transformedName, ClassNode targetClass) { if (this.plugin != null) { + Section pluginTimer = this.profiler.begin("plugin"); this.plugin.preApply(transformedName, targetClass, this.className, this); + pluginTimer.end(); } } @@ -1188,7 +1207,9 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ public void postApply(String transformedName, ClassNode targetClass) { if (this.plugin != null) { + Section pluginTimer = this.profiler.begin("plugin"); this.plugin.postApply(transformedName, targetClass, this.className, this); + pluginTimer.end(); } this.parent.postApply(transformedName, targetClass); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java index eb795020..bc97c423 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java @@ -56,6 +56,8 @@ import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Bytecode.Visibility; import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.perf.Profiler; +import org.spongepowered.asm.util.perf.Profiler.Section; import org.spongepowered.asm.util.throwables.SyntheticBridgeException; /** @@ -134,6 +136,8 @@ class MixinPreProcessorStandard { protected final MixinEnvironment env; + protected final Profiler profiler = MixinEnvironment.getProfiler(); + private final boolean verboseLogging, strictUnique; private boolean prepared, attached; @@ -151,13 +155,15 @@ class MixinPreProcessorStandard { * * @return Prepared classnode */ - MixinPreProcessorStandard prepare() { + final MixinPreProcessorStandard prepare() { if (this.prepared) { return this; } this.prepared = true; + Section prepareTimer = this.profiler.begin("prepare"); + for (MixinMethodNode mixinMethod : this.classNode.mixinMethods) { Method method = this.mixin.getClassInfo().findMethod(mixinMethod); this.prepareMethod(mixinMethod, method); @@ -167,6 +173,7 @@ class MixinPreProcessorStandard { this.prepareField(mixinField); } + prepareTimer.end(); return this; } @@ -201,17 +208,21 @@ class MixinPreProcessorStandard { // stub } - MixinPreProcessorStandard conform(TargetClassContext target) { + final MixinPreProcessorStandard conform(TargetClassContext target) { return this.conform(target.getClassInfo()); } - MixinPreProcessorStandard conform(ClassInfo target) { + final MixinPreProcessorStandard conform(ClassInfo target) { + Section conformTimer = this.profiler.begin("conform"); + for (MixinMethodNode mixinMethod : this.classNode.mixinMethods) { if (mixinMethod.isInjector()) { Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL); this.conformInjector(target, mixinMethod, method); } } + + conformTimer.end(); return this; } @@ -232,19 +243,27 @@ class MixinPreProcessorStandard { * * @param context mixin target context */ - MixinPreProcessorStandard attach(MixinTargetContext context) { + final MixinPreProcessorStandard attach(MixinTargetContext context) { if (this.attached) { throw new IllegalStateException("Preprocessor was already attached"); } this.attached = true; + Section attachTimer = this.profiler.begin("attach"); + // Perform context-sensitive attachment phase + Section timer = this.profiler.begin("methods"); this.attachMethods(context); + timer = timer.next("fields"); this.attachFields(context); // Apply transformations to the mixin bytecode + timer = timer.next("transform"); this.transform(context); + timer.end(); + + attachTimer.end(); return this; } @@ -637,21 +656,42 @@ class MixinPreProcessorStandard { for (Iterator iter = mixinMethod.instructions.iterator(); iter.hasNext();) { AbstractInsnNode insn = iter.next(); if (insn instanceof MethodInsnNode) { - MethodInsnNode methodNode = (MethodInsnNode)insn; - Method method = ClassInfo.forName(methodNode.owner).findMethodInHierarchy(methodNode, SearchType.ALL_CLASSES, - ClassInfo.INCLUDE_PRIVATE); - if (method != null && method.isRenamed()) { - methodNode.name = method.getName(); - } + this.transformMethod((MethodInsnNode)insn); } else if (insn instanceof FieldInsnNode) { - FieldInsnNode fieldNode = (FieldInsnNode)insn; - Field field = ClassInfo.forName(fieldNode.owner).findField(fieldNode, ClassInfo.INCLUDE_PRIVATE); - if (field != null && field.isRenamed()) { - fieldNode.name = field.getName(); - } + this.transformField((FieldInsnNode)insn); } } } } + protected void transformMethod(MethodInsnNode methodNode) { + Section metaTimer = this.profiler.begin("meta"); + ClassInfo owner = ClassInfo.forName(methodNode.owner); + if (owner == null) { + throw new RuntimeException(new ClassNotFoundException(methodNode.owner.replace('/', '.'))); + } + + Method method = owner.findMethodInHierarchy(methodNode, SearchType.ALL_CLASSES, ClassInfo.INCLUDE_PRIVATE); + metaTimer.end(); + + if (method != null && method.isRenamed()) { + methodNode.name = method.getName(); + } + } + + protected void transformField(FieldInsnNode fieldNode) { + Section metaTimer = this.profiler.begin("meta"); + ClassInfo owner = ClassInfo.forName(fieldNode.owner); + if (owner == null) { + throw new RuntimeException(new ClassNotFoundException(fieldNode.owner.replace('/', '.'))); + } + + Field field = owner.findField(fieldNode, ClassInfo.INCLUDE_PRIVATE); + metaTimer.end(); + + if (field != null && field.isRenamed()) { + fieldNode.name = field.getName(); + } + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java index a521aec1..308bc8b7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -27,16 +27,10 @@ package org.spongepowered.asm.mixin.transformer; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; +import java.lang.reflect.Method; import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.UUID; +import java.util.*; +import java.util.Map.Entry; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; @@ -68,6 +62,8 @@ import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; import org.spongepowered.asm.transformers.TreeTransformer; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.PrettyPrinter; +import org.spongepowered.asm.util.perf.Profiler; +import org.spongepowered.asm.util.perf.Profiler.Section; import net.minecraft.launchwrapper.IClassTransformer; import net.minecraft.launchwrapper.Launch; @@ -362,10 +358,12 @@ public class MixinTransformer extends TreeTransformer { if (force || environment.getOption(Option.DEBUG_EXPORT)) { String filter = environment.getOptionValue(Option.DEBUG_EXPORT_FILTER); if (force || filter == null || this.applyFilter(filter, transformedName)) { + Section exportTimer = MixinEnvironment.getProfiler().begin("debug.export"); File outputFile = this.dumpClass(transformedName.replace('.', '/'), bytes); if (this.decompiler != null) { this.decompiler.decompile(outputFile); } + exportTimer.end(); } } } @@ -435,6 +433,11 @@ public class MixinTransformer extends TreeTransformer { * Postprocessor for passthrough */ private final MixinPostProcessor postProcessor; + + /** + * Profiler + */ + private final Profiler profiler; /** * Current environment @@ -478,6 +481,8 @@ public class MixinTransformer extends TreeTransformer { this.generators.add(ArgsClassGenerator.getInstance()); this.generators.add(InnerClassGenerator.getInstance()); + + this.profiler = MixinEnvironment.getProfiler(); } private IHotSwap initHotSwapper() { @@ -527,6 +532,105 @@ public class MixinTransformer extends TreeTransformer { auditLogger.error("Could not force-load " + target, ex); } } + + if (MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_PROFILER)) { + this.printProfilerSummary(); + } + } + + private void printProfilerSummary() { + DecimalFormat threedp = new DecimalFormat("(###0.000"); + DecimalFormat onedp = new DecimalFormat("(###0.0"); + PrettyPrinter printer = this.profiler.printer(false, true); + + long prepareTime = this.profiler.get("mixin.prepare").getTotalTime(); + long readTime = this.profiler.get("mixin.read").getTotalTime(); + long applyTime = this.profiler.get("mixin.apply").getTotalTime(); + long writeTime = this.profiler.get("mixin.write").getTotalTime(); + long totalMixinTime = this.profiler.get("mixin").getTotalTime(); + + long loadTime = this.profiler.get("class.load").getTotalTime(); + long transformTime = this.profiler.get("class.transform").getTotalTime(); + long actualTime = totalMixinTime - loadTime - transformTime; + double timeSliceMixin = ((double)actualTime / (double)totalMixinTime) * 100.0D; + double timeSliceLoad = ((double)loadTime / (double)totalMixinTime) * 100.0D; + double timeSliceTransform = ((double)transformTime / (double)totalMixinTime) * 100.0D; + + long worstTransformerTime = 0L; + Section worstTransformer = null; + + for (Section section : this.profiler.getSections()) { + long transformerTime = section.getName().startsWith("class.transform.") ? section.getTotalTime() : 0L; + if (transformerTime > worstTransformerTime) { + worstTransformerTime = transformerTime; + worstTransformer = section; + } + } + + printer.hr().add("Summary").hr().add(); + + String format = "%9d ms %12s seconds)"; + printer.kv("Total mixin time", format, totalMixinTime, threedp.format(totalMixinTime * 0.001)).add(); + printer.kv("Preparing mixins", format, prepareTime, threedp.format(prepareTime * 0.001)); + printer.kv("Reading input", format, readTime, threedp.format(readTime * 0.001)); + printer.kv("Applying mixins", format, applyTime, threedp.format(applyTime * 0.001)); + printer.kv("Writing output", format, writeTime, threedp.format(writeTime * 0.001)).add(); + + printer.kv("of which",""); + printer.kv("Time spent loading from disk", format, loadTime, threedp.format(loadTime * 0.001)); + printer.kv("Time spent transforming classes", format, transformTime, threedp.format(transformTime * 0.001)).add(); + + if (worstTransformer != null) { + printer.kv("Worst transformer", worstTransformer.getName()); + printer.kv("Class", worstTransformer.getInfo()); + printer.kv("Time spent", "%s seconds", worstTransformer.getTotalSeconds()); + printer.kv("called", "%d times", worstTransformer.getTotalCount()).add(); + } + + printer.kv(" Time allocation: Processing mixins", "%9d ms %10s%% of total)", actualTime, onedp.format(timeSliceMixin)); + printer.kv("Loading classes", "%9d ms %10s%% of total)", loadTime, onedp.format(timeSliceLoad)); + printer.kv("Running transformers", "%9d ms %10s%% of total)", transformTime, onedp.format(timeSliceTransform)); + printer.add(); + + try { + Class agent = Class.forName("org.spongepowered.metronome.Agent", false, Launch.class.getClassLoader()); + Method mdGetTimes = agent.getDeclaredMethod("getTimes"); + + @SuppressWarnings("unchecked") + Map times = (Map)mdGetTimes.invoke(null); + + printer.hr().add("Transformer Times").hr().add(); + + int longest = 10; + for (Entry entry : times.entrySet()) { + longest = Math.max(longest, entry.getKey().length()); + } + + for (Entry entry : times.entrySet()) { + String name = entry.getKey(); + long mixinTime = 0L; + for (Section section : this.profiler.getSections()) { + if (name.equals(section.getInfo())) { + mixinTime = section.getTotalTime(); + break; + } + } + + if (mixinTime > 0L) { + printer.add("%-" + longest + "s %8s ms %8s ms in mixin)", name, entry.getValue() + mixinTime, "(" + mixinTime); + } else { + printer.add("%-" + longest + "s %8s ms", name, entry.getValue()); + } + } + + printer.add(); + + } catch (Throwable th) { + // Metronome agent not loaded + } + + + printer.print(); } /* (non-Javadoc) @@ -541,7 +645,9 @@ public class MixinTransformer extends TreeTransformer { if (basicClass == null) { for (IClassGenerator generator : this.generators) { + Section genTimer = this.profiler.begin("generator.", generator.getClass().getSimpleName().toLowerCase()); if ((basicClass = generator.generate(transformedName)) != null) { + genTimer.end(); this.exporter.export(transformedName.replace('.', '/'), false, basicClass); return basicClass; } @@ -552,19 +658,23 @@ public class MixinTransformer extends TreeTransformer { boolean locked = this.lock.push().check(); MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); - + Section mixinTimer = this.profiler.begin("mixin"); + if (!locked) { try { this.checkSelect(environment); } catch (Exception ex) { this.lock.pop(); + mixinTimer.end(); throw new MixinException(ex); } } try { if (this.postProcessor.canTransform(transformedName)) { + Section postTimer = this.profiler.begin("postprocessor"); byte[] bytes = this.postProcessor.transform(name, transformedName, basicClass); + postTimer.end(); this.exporter.export(transformedName, false, bytes); return bytes; } @@ -605,8 +715,10 @@ public class MixinTransformer extends TreeTransformer { try { // Tree for target class + Section timer = this.profiler.begin("read"); ClassNode targetClassNode = this.readClass(basicClass, true); TargetClassContext context = new TargetClassContext(this.sessionId, transformedName, targetClassNode, mixins); + timer.end(); basicClass = this.applyMixins(context); this.transformedCount++; } catch (InvalidMixinException th) { @@ -622,6 +734,7 @@ public class MixinTransformer extends TreeTransformer { throw new MixinTransformerError("An unexpected critical error was encountered", th); } finally { this.lock.pop(); + mixinTimer.end(); } } @@ -662,20 +775,34 @@ public class MixinTransformer extends TreeTransformer { } String action = this.currentEnvironment == environment ? "Checking for additional" : "Preparing"; MixinTransformer.logger.log(this.verboseLoggingLevel, "{} mixins for {}", action, environment); - long startTime = System.currentTimeMillis(); + + this.profiler.setActive(true); + this.profiler.mark(environment.getPhase().toString() + ":prepare"); + Section prepareTimer = this.profiler.begin("prepare"); this.selectConfigs(environment); this.selectModules(environment); int totalMixins = this.prepareConfigs(environment); this.currentEnvironment = environment; this.transformedCount = 0; + + prepareTimer.end(); - double elapsedTime = (System.currentTimeMillis() - startTime) * 0.001D; + long elapsedMs = prepareTimer.getTime(); + double elapsedTime = prepareTimer.getSeconds(); if (elapsedTime > 0.25D) { + long loadTime = this.profiler.get("class.load").getTime(); + long transformTime = this.profiler.get("class.transform").getTime(); + long pluginTime = this.profiler.get("mixin.plugin").getTime(); String elapsed = new DecimalFormat("###0.000").format(elapsedTime); - String perMixinTime = new DecimalFormat("###0.0").format((elapsedTime / totalMixins) * 1000.0); - MixinTransformer.logger.log(this.verboseLoggingLevel, "Prepared {} mixins in {} sec ({} msec avg.)", totalMixins, elapsed, perMixinTime); + String perMixinTime = new DecimalFormat("###0.0").format(((double)elapsedMs) / totalMixins); + + MixinTransformer.logger.log(this.verboseLoggingLevel, "Prepared {} mixins in {} sec ({}ms avg) ({}ms load, {}ms transform, {}ms plugin)", + totalMixins, elapsed, perMixinTime, loadTime, transformTime, pluginTime); } + + this.profiler.mark(environment.getPhase().toString() + ":apply"); + this.profiler.setActive(environment.getOption(Option.DEBUG_PROFILER)); } /** @@ -801,8 +928,11 @@ public class MixinTransformer extends TreeTransformer { * @return class bytecode after application of mixins */ private byte[] applyMixins(TargetClassContext context) { + Section timer = this.profiler.begin("preapply"); this.preApply(context); + timer = timer.next("apply"); this.apply(context); + timer = timer.next("postapply"); try { this.postApply(context); } catch (ValidationFailedException ex) { @@ -812,6 +942,7 @@ public class MixinTransformer extends TreeTransformer { this.writeClass(context); } } + timer.end(); return this.writeClass(context); } @@ -927,7 +1058,9 @@ public class MixinTransformer extends TreeTransformer { private byte[] writeClass(String transformedName, ClassNode targetClass, boolean forceExport) { // Collapse tree to bytes + Section writeTimer = this.profiler.begin("write"); byte[] bytes = this.writeClass(targetClass); + writeTimer.end(); this.exporter.export(transformedName, forceExport, bytes); return bytes; } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/TreeInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/TreeInfo.java index d8e69c04..65dd5d58 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/TreeInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/TreeInfo.java @@ -36,6 +36,8 @@ import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.transformer.MixinTransformer.ReEntranceState; import org.spongepowered.asm.util.launchwrapper.LaunchClassLoaderUtil; +import org.spongepowered.asm.util.perf.Profiler; +import org.spongepowered.asm.util.perf.Profiler.Section; import net.minecraft.launchwrapper.IClassTransformer; import net.minecraft.launchwrapper.Launch; @@ -87,10 +89,16 @@ abstract class TreeInfo { static byte[] loadClass(String className, boolean runTransformers) throws ClassNotFoundException, IOException { String transformedName = className.replace('/', '.'); String name = MixinEnvironment.getCurrentEnvironment().unmap(transformedName); + + Profiler profiler = MixinEnvironment.getProfiler(); + Section loadTime = profiler.begin(Profiler.ROOT, "class.load"); byte[] classBytes = TreeInfo.getClassBytes(name, transformedName); + loadTime.end(); if (runTransformers) { - classBytes = TreeInfo.applyTransformers(name, transformedName, classBytes); + Section transformTime = profiler.begin(Profiler.ROOT, "class.transform"); + classBytes = TreeInfo.applyTransformers(name, transformedName, classBytes, profiler); + transformTime.end(); } if (classBytes == null) { @@ -136,7 +144,7 @@ abstract class TreeInfo { * @return class bytecode after processing by all registered transformers * except the excluded transformers */ - private static byte[] applyTransformers(String name, String transformedName, byte[] basicClass) { + private static byte[] applyTransformers(String name, String transformedName, byte[] basicClass, Profiler profiler) { if (LaunchClassLoaderUtil.forClassLoader(Launch.classLoader).isClassExcluded(name, transformedName)) { return basicClass; } @@ -149,15 +157,19 @@ abstract class TreeInfo { TreeInfo.lock.clear(); } + Class clazz = transformer.getClass(); + Section transformTime = profiler.begin(Profiler.ROOT | Profiler.FINE, "class.transform", clazz.getSimpleName().toLowerCase()); + transformTime.setInfo(clazz.getName()); basicClass = transformer.transform(name, transformedName, basicClass); - + transformTime.end(); + if (TreeInfo.lock != null && TreeInfo.lock.isSet()) { // Also add it to the exclusion list so we can exclude it if the environment triggers a rebuild - environment.addTransformerExclusion(transformer.getClass().getName()); + environment.addTransformerExclusion(clazz.getName()); TreeInfo.lock.clear(); TreeInfo.logger.info("A re-entrant transformer '{}' was detected and will no longer process meta class data", - transformer.getClass().getName()); + clazz.getName()); } } diff --git a/src/main/java/org/spongepowered/asm/util/Counter.java b/src/main/java/org/spongepowered/asm/util/Counter.java new file mode 100644 index 00000000..d49bc399 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/Counter.java @@ -0,0 +1,47 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util; + +/** + * Mutable integer for use in collections + */ +public final class Counter { + + /** + * Mutable int value + */ + public int value; + + @Override + public boolean equals(Object obj) { + return obj != null && obj.getClass() == Counter.class && ((Counter)obj).value == this.value; + } + + @Override + public int hashCode() { + return this.value; + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/perf/Profiler.java b/src/main/java/org/spongepowered/asm/util/perf/Profiler.java new file mode 100644 index 00000000..484b47a7 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/perf/Profiler.java @@ -0,0 +1,718 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util.perf; + +import java.text.DecimalFormat; +import java.util.*; + +import org.spongepowered.asm.util.PrettyPrinter; +import org.spongepowered.asm.util.PrettyPrinter.Alignment; + +import com.google.common.base.Joiner; + +/** + * Performance profiler for Mixin. + */ +public final class Profiler { + + /** + * Flag to indicate a root section. Root sections are always recorded at the + * root wherever they occur, but may appear under other sections in order to + * show the time share of the root section relative to the parent. + */ + public static final int ROOT = 0x01; + + /** + * Flag to indicate a fine section. Fine sections are always recorded, but + * are only displayed in the printed output if the includeFine flag is set. + */ + public static final int FINE = 0x02; + + /** + * Profiler section. Normal sections do nothing so that the profiler itself + * consumes minimal resources when disabled. + */ + public class Section { + + /** + * Section name + */ + private final String name; + + /** + * True if this is a FINE section + */ + private boolean fine; + + /** + * Auxilliary info for this section, used for context + */ + private String info; + + Section(String name) { + this.name = name; + this.info = name; + } + + /** + * Get the delegate (root section) for this section + */ + Section getDelegate() { + return this; + } + + /** + * Set this section as FINE + */ + Section setFine(boolean fine) { + this.fine = fine; + return this; + } + + /** + * Get whether this section is FINE + */ + public boolean isFine() { + return this.fine; + } + + /** + * Get the section name + */ + public String getName() { + return this.name; + } + + /** + * Get the base name for this section, for delegated sections this is + * the name of the parent section, minus the root + */ + public String getBaseName() { + return this.name; + } + + /** + * Set the auxilliary info for this section + * + * @param info aux info + */ + public void setInfo(String info) { + this.info = info; + } + + /** + * Get the auxilliary info for this section + */ + public String getInfo() { + return this.info; + } + + /** + * Start timing on this section + * + * @return fluent + */ + Section start() { + return this; + } + + /** + * Stop timing of this section + * + * @return fluent + */ + protected Section stop() { + return this; + } + + /** + * Stop timing of this section and end it (pop from profiler stack) + * + * @return fluent + */ + public Section end() { + return this; + } + + /** + * Stop timing of this section and start a new section at the same level + * + * @param name name of the next section + * @return new section + */ + public Section next(String name) { + this.end(); + return Profiler.this.begin(name); + } + + /** + * Mark off a profiling slice in this section. Each timing slice is used + * to benchmark a different phase of operations. Calling this method + * pushes the current time into the times array and resets the time and + * counter to zero + */ + void mark() { + } + + /** + * Get the current time in milliseconds in the current phase + */ + public long getTime() { + return 0; + } + + /** + * Get the current time in milliseconds in all phases + */ + public long getTotalTime() { + return 0; + } + + /** + * Get the current time in seconds in the current phase + */ + public double getSeconds() { + return 0.0D; + } + + /** + * Get the current time in seconds in all phases + */ + public double getTotalSeconds() { + return 0.0D; + } + + /** + * Get all available time slices including the current one in + * milliseconds + */ + public long[] getTimes() { + return new long[1]; + } + + /** + * Get the number of total time periods recorded in the current slice + */ + public int getCount() { + return 0; + } + + /** + * Get the number of total time periods recorded in the all slices + */ + public int getTotalCount() { + return 0; + } + + /** + * Get the average time in milliseconds of each time period recorded in + * the current slice + */ + public double getAverageTime() { + return 0.0D; + } + + /** + * Get the average time in milliseconds of each time period recorded in + * the all slices + */ + public double getTotalAverageTime() { + return 0.0D; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public final String toString() { + return this.name; + } + + } + + /** + * Live profiler section. Actually records timings for when the profiler is + * active. + */ + class LiveSection extends Section { + + /** + * Cursor points at the current active time slice. The current time + * slice is not in the array of times. + */ + private int cursor = 0; + + /** + * Historical time slicess (times recorded by calls to {@link #mark}) + */ + private long[] times = new long[0]; + + /** + * Start time. Zero when not recording a time slice + */ + private long start = 0L; + + /** + * Current accumulated time and time in all previous slices + */ + private long time, markedTime; + + /** + * Current period count and period count in all previous slices + */ + private int count, markedCount; + + LiveSection(String name, int cursor) { + super(name); + this.cursor = cursor; + } + + @Override + Section start() { + this.start = System.currentTimeMillis(); + return this; + } + + @Override + protected Section stop() { + if (this.start > 0L) { + this.time += System.currentTimeMillis() - this.start; + } + this.start = 0L; + this.count++; + return this; + } + + @Override + public Section end() { + this.stop(); + Profiler.this.end(this); + return this; + } + + @Override + void mark() { + if (this.cursor >= this.times.length) { + this.times = Arrays.copyOf(this.times, this.cursor + 4); + } + this.times[this.cursor] = this.time; + this.markedTime += this.time; + this.markedCount += this.count; + this.time = 0; + this.count = 0; + this.cursor++; + } + + @Override + public long getTime() { + return this.time; + } + + @Override + public long getTotalTime() { + return this.time + this.markedTime; + } + + @Override + public double getSeconds() { + return this.time * 0.001D; + } + + @Override + public double getTotalSeconds() { + return (this.time + this.markedTime) * 0.001D; + } + + @Override + public long[] getTimes() { + long[] times = new long[this.cursor + 1]; + System.arraycopy(this.times, 0, times, 0, Math.min(this.times.length, this.cursor)); + times[this.cursor] = this.time; + return times; + } + + @Override + public int getCount() { + return this.count; + } + + @Override + public int getTotalCount() { + return this.count + this.markedCount; + } + + @Override + public double getAverageTime() { + return this.count > 0 ? (double)(this.time) / this.count : 0.0D; + } + + @Override + public double getTotalAverageTime() { + return this.count > 0 ? (double)(this.time + this.markedTime) / (this.count + this.markedCount) : 0.0D; + } + + } + + /** + * Sub-profiler-section, acts as a delegate to a root section when recording + * a root section under another parent. Calls to methods in this section are + * handled locally and in the delegated root. + */ + class SubSection extends LiveSection { + + /** + * Section base name + */ + private final String baseName; + + /** + * Delegated root + */ + private final Section root; + + SubSection(String name, int cursor, String baseName, Section root) { + super(name, cursor); + this.baseName = baseName; + this.root = root; + } + + @Override + public String getBaseName() { + return this.baseName; + } + + @Override + public void setInfo(String info) { + this.root.setInfo(info); + super.setInfo(info); + } + + @Override + Section getDelegate() { + return this.root; + } + + @Override + Section start() { + this.root.start(); + return super.start(); + } + + @Override + public Section end() { + this.root.stop(); + return super.end(); + } + + @Override + public Section next(String name) { + super.stop(); + return this.root.next(name); + } + + } + + /** + * All profiler sections + */ + private final Map sections = new TreeMap(); + + /** + * Profiler phases, recorded by calling {@link #mark} + */ + private final List phases = new ArrayList(); + + /** + * Profiler section stack + */ + private final Deque
stack = new LinkedList
(); + + /** + * True when profiler is active + */ + private boolean active; + + public Profiler() { + this.phases.add("Initial"); + } + + /** + * Set the active state of the profiler. When activating the profiler is + * always reset. + * + * @param active new active state + */ + public void setActive(boolean active) { + if ((!this.active && active) || !active) { + this.reset(); + } + this.active = active; + } + + /** + * Reset all profiler state + */ + public void reset() { + this.sections.clear(); + this.phases.clear(); + this.phases.add("Initial"); + this.stack.clear(); + } + + /** + * Get the specified profiler section + * + * @param name section name + * @return profiler section + */ + public Section get(String name) { + Section section = this.sections.get(name); + if (section == null) { + section = this.active ? new LiveSection(name, this.phases.size() - 1) : new Section(name); + this.sections.put(name, section); + } + + return section; + } + + private Section getSubSection(String name, String baseName, Section root) { + Section section = this.sections.get(name); + if (section == null) { + section = new SubSection(name, this.phases.size() - 1, baseName, root); + this.sections.put(name, section); + } + + return section; + } + + boolean isHead(Section section) { + return this.stack.peek() == section; + } + + /** + * Begin a new profiler section using the specified path + * + * @param path path parts + * @return new profiler section + */ + public Section begin(String... path) { + return this.begin(0, path); + } + + /** + * Begin a new profiler section using the specified path and flags + * + * @param flags section flags + * @param path path parts + * @return new profiler section + */ + public Section begin(int flags, String... path) { + return this.begin(flags, Joiner.on('.').join(path)); + } + + /** + * Begin a new profiler section using the specified name + * + * @param name section name + * @return new profiler section + */ + public Section begin(String name) { + return this.begin(0, name); + } + + /** + * Begin a new profiler section using the specified name and flags + * + * @param flags section flags + * @param name section name + * @return new profiler section + */ + public Section begin(int flags, String name) { + boolean root = (flags & Profiler.ROOT) != 0; + boolean fine = (flags & Profiler.FINE) != 0; + + String path = name; + Section head = this.stack.peek(); + if (head != null) { + path = head.getName() + (root ? " -> " : ".") + path; + } + + Section section = this.get(root ? name : path); + if (root && head != null && this.active) { + section = this.getSubSection(path, head.getName(), section); + } + + section.setFine(fine); + this.stack.push(section); + return section.start(); + } + + /** + * Callback from section when {@link Section#end} is called, pops the + * section from the profiler stack + * + * @param section section ending + */ + void end(Section section) { + for (Section head = this.stack.pop(), next = head; next != section; next = this.stack.pop()) { + if (next == null) { + if (head == null) { + throw new IllegalStateException("Attempted to pop " + section + " but the stack is empty"); + } + throw new IllegalStateException("Attempted to pop " + section + " which was not in the stack, head was " + head); + } + } + } + + /** + * Mark a new phase (time slice) for this profiler, all sections record + * their current times and then reset to zero. If no times have been + * recorded in the current phase, the phase is discarded. + * + * @param phase Name of the phase + */ + public void mark(String phase) { + long currentPhaseTime = 0L; + for (Section section : this.sections.values()) { + currentPhaseTime += section.getTime(); + } + + // If no accumulated time in the current phase, just discard it + if (currentPhaseTime == 0L) { + int size = this.phases.size(); + this.phases.set(size - 1, phase); + return; + } + + this.phases.add(phase); + for (Section section : this.sections.values()) { + section.mark(); + } + } + + /** + * Get all recorded profiler sections + */ + public Collection
getSections() { + return Collections.
unmodifiableCollection(this.sections.values()); + } + + /** + * Get the profiler state with all sections in a {@link PrettyPrinter}. + * + * @param includeFine Include sections marked as FINE + * @param group Group delegated sections with their root instead of in the + * normal alphabetical order + * @return PrettyPrinter with section data + */ + public PrettyPrinter printer(boolean includeFine, boolean group) { + PrettyPrinter printer = new PrettyPrinter(); + + // 4 extra columns, name, total, count, avg + int colCount = this.phases.size() + 4; + + // Which columns go where + // Name Total Phases Count Average + // | | | | | + int[] columns = { 0, 1, 2, colCount - 2, colCount - 1 }; + + Object[] headers = new Object[(colCount) * 2]; + for (int col = 0, pos = 0; col < colCount; col++, pos = col * 2) { + headers[pos + 1] = Alignment.RIGHT; + if (col == columns[0]) { + headers[pos] = (group ? "" : " ") + "Section"; + headers[pos + 1] = Alignment.LEFT; + } else if (col == columns[1]) { + headers[pos] = " TOTAL"; + } else if (col == columns[3]) { + headers[pos] = " Count"; + } else if (col == columns[4]) { + headers[pos] = "Avg. "; + } else if (col - columns[2] < this.phases.size()) { + headers[pos] = this.phases.get(col - columns[2]); + } else { + headers[pos] = ""; + } + } + + printer.table(headers).th().hr().add(); + + for (Section section : this.sections.values()) { + if ((section.isFine() && !includeFine) || (group && section.getDelegate() != section)) { + continue; + } + + // Add row for this section + this.printSectionRow(printer, colCount, columns, section, group); + + // If grouping, print sections which have this section as delegate + if (group) { + for (Section subSection : this.sections.values()) { + Section delegate = subSection.getDelegate(); + if ((subSection.isFine() && !includeFine) || delegate != section || delegate == subSection) { + continue; + } + + this.printSectionRow(printer, colCount, columns, subSection, group); + } + } + } + + return printer.add(); + } + + private void printSectionRow(PrettyPrinter printer, int colCount, int[] columns, Section section, boolean group) { + boolean isDelegate = section.getDelegate() != section; + Object[] values = new Object[colCount]; + int col = 1; + if (group) { + values[0] = isDelegate ? " > " + section.getBaseName() : section.getName(); + } else { + values[0] = (isDelegate ? "+ " : " ") + section.getName(); + } + + long[] times = section.getTimes(); + for (long time : times) { + if (col == columns[1]) { + values[col++] = section.getTotalTime() + " ms"; + } + if (col >= columns[2] && col < values.length) { + values[col++] = time + " ms"; + } + } + + values[columns[3]] = section.getTotalCount(); + values[columns[4]] = new DecimalFormat(" ###0.000 ms").format(section.getTotalAverageTime()); + + for (int i = 0; i < values.length; i++) { + if (values[i] == null) { + values[i] = "-"; + } + } + + printer.tr(values); + } + +}