Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ public static void main(String[] args) {
de.peeeq.wurstio.languageserver.ModelManager modelManager =
new de.peeeq.wurstio.languageserver.ModelManagerImpl(root.toFile(), new de.peeeq.wurstio.languageserver.BufferManager());
// checked once by the build, after the map script with the project config is in the model
modelManager.loadProject();
cliBuildMap.getTimeTaker().measure("Load project", modelManager::loadProject);
Object result = cliBuildMap.execute(modelManager);
WLogger.info("map build success");
System.out.println("Build succeeded. Output file: <" + result + ">");
Expand Down
133 changes: 85 additions & 48 deletions de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/TimeTaker.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package de.peeeq.wurstio;

import de.peeeq.wurstscript.utils.CompilationCancellation;
import de.peeeq.wurstscript.utils.Utils;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

Expand Down Expand Up @@ -51,73 +54,107 @@ public void printReport() {
}
}

/**
* Records the time of each measured step and phase, nested as they run. A phase begun inside another phase
* or step is a part of it, and {@link #endPhase()} ends the innermost open phase; a step ends the phases left
* open inside it. The report shows each step under the one it ran in, and what the steps of a level do not
* account for, so that the parts add up to the total, which runs from the creation of the recorder.
*/
class Recording implements TimeTaker {
private int nesting = 0;
private String currentPhaseDescription;
private long currentPhaseStart;
private final Map<String, Long> accumulatedTimes = new LinkedHashMap<>();
private final long startTime = System.nanoTime();
/** Accumulated nanoseconds per step, by its path of enclosing steps; in the order the steps first began. */
private final Map<List<String>, Long> accumulatedTimes = new LinkedHashMap<>();
private final Deque<Open> open = new ArrayDeque<>();

private Long startTime = 0L;
private record Open(List<String> path, long start, boolean phase) {
}

@Override
public <T> T measure(String name, Supplier<T> f) {
CompilationCancellation.check();
name = withNesting(name);
nesting++;
accumulatedTimes.putIfAbsent(name, 0L);
long time = System.currentTimeMillis();
T result = f.get();
long duration = System.currentTimeMillis() - time;
reportDuration(name, duration);
nesting--;
return result;
Open step = begin(name, false);
try {
return f.get();
} finally {
while (!open.isEmpty() && open.peek() != step) {
end();
}
if (!open.isEmpty()) {
end();
}
}
}

private String withNesting(String name) {
return Utils.repeat(' ', nesting) + name;
@Override
public void beginPhase(String description) {
begin(description, true);
}

private void reportDuration(String name, long duration) {
accumulatedTimes.put(name, accumulatedTimes.getOrDefault(name, 0L) + duration);
@Override
public void endPhase() {
// an end without a phase open in the current step is ignored: it must not end the step
if (!open.isEmpty() && open.peek().phase()) {
end();
}
}

private Open begin(String name, boolean phase) {
List<String> path = new ArrayList<>(open.isEmpty() ? List.of() : open.peek().path());
path.add(name);
List<String> key = List.copyOf(path);
accumulatedTimes.putIfAbsent(key, 0L);
Open step = new Open(key, System.nanoTime(), phase);
open.push(step);
return step;
}

@Override
public void beginPhase(String description) {
if (accumulatedTimes.isEmpty()) {
this.startTime = System.currentTimeMillis();
}
if (currentPhaseDescription != null) {
endPhase();
private void end() {
Open step = open.pop();
accumulatedTimes.merge(step.path(), System.nanoTime() - step.start(), Long::sum);
}

/** The report, with the phases still open ended now. */
public String report() {
while (!open.isEmpty()) {
end();
}
description = withNesting(description);
nesting++;
accumulatedTimes.putIfAbsent(description, 0L);
currentPhaseDescription = description;
currentPhaseStart = System.currentTimeMillis();
long total = System.nanoTime() - startTime;
StringBuilder sb = new StringBuilder();
sb.append("#############################\n");
sb.append("Run times:\n");
appendLevel(sb, List.of(), total);
sb.append("Total runtime: ").append(ms(total)).append("ms\n");
sb.append("GC time: ").append(getGarbageCollectionTime()).append("ms\n");
return sb.toString();
}

@Override
public void endPhase() {
if (currentPhaseDescription == null) {
return;
private void appendLevel(StringBuilder sb, List<String> parent, long parentTime) {
long accounted = 0;
boolean any = false;
for (Map.Entry<List<String>, Long> e : accumulatedTimes.entrySet()) {
List<String> path = e.getKey();
if (path.size() != parent.size() + 1 || !path.subList(0, parent.size()).equals(parent)) {
continue;
}
any = true;
accounted += e.getValue();
sb.append(" ".repeat(2 * parent.size())).append(path.get(path.size() - 1)).append(": ")
.append(ms(e.getValue())).append("ms\n");
appendLevel(sb, path, e.getValue());
}
if (any && parentTime - accounted >= 1_000_000L) {
sb.append(" ".repeat(2 * parent.size())).append("(not measured): ")
.append(ms(parentTime - accounted)).append("ms\n");
}
long duration = System.currentTimeMillis() - currentPhaseStart;
reportDuration(currentPhaseDescription, duration);
nesting--;
currentPhaseDescription = null;
}

private static long ms(long nanos) {
return nanos / 1_000_000L;
}

@Override
public void printReport() {
System.out.println("#############################");
System.out.println("Run times:");

for (Map.Entry<String, Long> e : accumulatedTimes.entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue() + "ms");
}

System.out.println("Total runtime: " + (System.currentTimeMillis() - startTime) + "ms");
System.out.println("GC time: " + getGarbageCollectionTime() + "ms");
System.out.print(report());
}

private static long getGarbageCollectionTime() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ public void runCompiletime(WurstProjectConfigData projectConfigData, boolean isP
// compile & inject object-editor data
// TODO run optimizations later?
gui.sendProgress("Running compiletime functions");
timeTaker.beginPhase("run compiletime functions");
// Use try-with-resources to release open native resources (e.g., SQLite DB handles) after compiletime execution finishes.
try (CompiletimeFunctionRunner ctr = new CompiletimeFunctionRunner(imTranslator, getImProg(), getMapFile(), getMapfileMpqEditor(), gui,
CompiletimeFunctions, projectConfigData, isProd, cache)) {
Expand All @@ -138,6 +139,7 @@ public void runCompiletime(WurstProjectConfigData projectConfigData, boolean isP
ctr.setOutputStream(new PrintStream(System.err));
ctr.run();
}
timeTaker.endPhase();
}

if (gui.getErrorCount() > 0) {
Expand Down Expand Up @@ -473,6 +475,7 @@ public JassProg transformProgToJass() {
timeTaker.endPhase();
}

beginPhase(4, "eliminate varargs");
new VarargEliminator(imProg2).run();
printDebugImProg("./test-output/im " + stage++ + "_varargEliminated.im");
imTranslator2.assertProperties();
Expand Down Expand Up @@ -575,6 +578,7 @@ public JassProg transformProgToJass() {
beginPhase(13, "froptimize");
optimizer.optimize();
printDebugImProg("./test-output/im " + stage++ + "_afteroptimize.im");
timeTaker.endPhase();
}


Expand All @@ -584,13 +588,21 @@ public JassProg transformProgToJass() {
// the last removal was followed by nothing which makes garbage (the code for the hot reload only calls and sets)
optimizer.assertNoGarbage("only the code for the hot reload was added since the last removal");
// the package initialisers which are empty now are removed, and then the variables only they used
timeTaker.beginPhase("remove empty package inits");
imTranslator.removeEmptyPackageInits();
timeTaker.endPhase();
timeTaker.beginPhase("remove garbage");
optimizer.removeGarbage();
timeTaker.endPhase();
imTranslator.assertFlat("before it is translated to Jass, which has no statement expression");
timeTaker.beginPhase("call relations");
getImTranslator().calculateCallRelationsAndReadVariables();
timeTaker.endPhase();
timeTaker.beginPhase("print IM as Jass");
ImToJassTranslator translator =
new ImToJassTranslator(getImProg(), getImTranslator().getCalledFunctions(), getImTranslator().getMainFunc(), getImTranslator().getConfFunc());
prog = translator.translate();
timeTaker.endPhase();
if (errorHandler.getErrorCount() > 0) {
prog = null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ protected File compileMap(ModelManager modelManager, File projectFolder, WurstGu
purgeUnimportedFiles(modelManager, model);

gui.sendProgress("Check program");
checkModel(modelManager, compiler, model, runArgs);
timeTaker.measure("Typecheck program", () -> checkModel(modelManager, compiler, model, runArgs));

if (gui.getErrorCount() > 0) {
throw new RequestFailedException(MessageType.Warning, "Could not compile project: ", gui.getErrorList().get(0));
Expand All @@ -256,15 +256,16 @@ protected File compileMap(ModelManager modelManager, File projectFolder, WurstGu

if (runArgs.isLua()) {
print("Translating program to Lua ... ");
Optional<LuaCompilationUnit> luaCode = Optional.ofNullable(compiler.transformProgToLua());
Optional<LuaCompilationUnit> luaCode = Optional.ofNullable(
timeTaker.measure("Transform program to Lua", compiler::transformProgToLua));

if (!luaCode.isPresent()) {
print("Could not compile project\n");
throw new RuntimeException("Could not compile project (error in LUA translation)");
}

StringBuilder sb = new StringBuilder();
luaCode.get().print(sb, 0);
timeTaker.measure("Print Lua", () -> luaCode.get().print(sb, 0));

String compiledMapScript = sb.toString();
LuaTranslator.assertNoLeakedHashtableNativeCalls(compiledMapScript);
Expand All @@ -276,7 +277,7 @@ protected File compileMap(ModelManager modelManager, File projectFolder, WurstGu

} else {
print("Translating program to jass ... ");
compiler.transformProgToJass();
timeTaker.measure("Transform program to Jass", compiler::transformProgToJass);

Optional<JassProg> jassProg = Optional.ofNullable(compiler.getProg());
if (!jassProg.isPresent()) {
Expand All @@ -286,7 +287,7 @@ protected File compileMap(ModelManager modelManager, File projectFolder, WurstGu

gui.sendProgress("Printing program");
JassPrinter printer = new JassPrinter(!runArgs.isOptimize(), jassProg.get());
String compiledMapScript = printer.printProg();
String compiledMapScript = timeTaker.measure("Print Jass", () -> printer.printProg());
File buildDir = getBuildDir();
File outFile = new File(buildDir, BUILD_COMPILED_JASS_NAME);
Files.write(compiledMapScript.getBytes(Charsets.UTF_8), outFile);
Expand Down Expand Up @@ -455,13 +456,17 @@ protected File compileScript(WurstGui gui, ModelManager modelManager, List<Strin
// A shared-model rebuild must finish as a unit; cancellation resumes on the
// private compilation copy, rather than leaving editor state half initialized.
CompilationCancellation.run(() -> false, () -> {
modelManager.clean();
modelManager.buildProject();
timeTaker.measure("Rebuild project", () -> {
modelManager.clean();
modelManager.buildProject();
});
});
}

timeTaker.beginPhase("Replace map script");
replaceBaseScriptWithConfig(modelManager, scriptFile);
checkModelWithMapScript(modelManager, gui, runArgs);
timeTaker.endPhase();
timeTaker.measure("Typecheck project with map script", () -> checkModelWithMapScript(modelManager, gui, runArgs));

if (modelManager.hasErrors()) {
for (CompileError compileError : modelManager.getParseErrors()) {
Expand All @@ -475,7 +480,8 @@ protected File compileScript(WurstGui gui, ModelManager modelManager, List<Strin
|| CompilationCancellation.isScoped()) {
// compilation will alter the model (e.g. remove unused imports),
// so it is safer to create a copy
model = ModelManager.copy(model);
WurstModel original = model;
model = timeTaker.measure("Copy model", () -> ModelManager.copy(original));
}

return compileMap(modelManager, modelManager.getProjectPath(), gui, mapCopy, runArgs, model, projectConfigData, isProd);
Expand Down Expand Up @@ -733,7 +739,9 @@ protected CompilationResult compileScript(ModelManager modelManager, WurstGui gu

if (!runArgs.isHotReload()) {
// Ensure we're working with the cached map
timeTaker.beginPhase("Prepare cached map");
File cachedMap = ensureCachedMap(gui);
timeTaker.endPhase();

// Update testMap to point to cached map
testMap = Optional.of(cachedMap);
Expand Down Expand Up @@ -876,7 +884,9 @@ protected File executeBuildMapPipeline(ModelManager modelManager, WurstGui gui,

CompilationResult result = compileScript(modelManager, gui, Optional.of(targetMapFile), projectConfig, buildDir, isProductionBuild());
injectMapData(gui, Optional.of(targetMapFile), result);
timeTaker.beginPhase("Write requested script");
writeRequestedScript(result);
timeTaker.endPhase();

targetMapFile = ensureWritableBuildOutput(targetMapFile, true);
CompilationCancellation.check();
Expand All @@ -885,7 +895,9 @@ protected File executeBuildMapPipeline(ModelManager modelManager, WurstGui gui,
// honoring cancellation. Otherwise the output could replace a valid release with
// an unfinished cached map.
CompilationCancellation.run(() -> false, () -> {
timeTaker.beginPhase("Copy output map");
java.nio.file.Files.copy(getCachedMapFile().toPath(), outputMapFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
timeTaker.endPhase();

gui.sendProgress("Finalizing map");
try (MpqEditor mpq = MpqEditorFactory.getEditor(Optional.of(outputMapFile))) {
Expand All @@ -894,13 +906,16 @@ protected File executeBuildMapPipeline(ModelManager modelManager, WurstGui gui,
// not be present in the distributed map.
if (mpq.hasFile("wurst_cache_manifest.txt")) mpq.deleteFile("wurst_cache_manifest.txt");
if (mpq.hasFile("wurst_object_cache.txt")) mpq.deleteFile("wurst_object_cache.txt");
timeTaker.beginPhase("Finalize map");
mpq.closeWithCompression();
timeTaker.endPhase();
}
}

});

gui.sendProgress("Done.");
timeTaker.printReport();
Comment thread
Frotty marked this conversation as resolved.
Resolved
return targetMapFile;
}

Expand Down
Loading
Loading