Skip to content

Instantly share code, notes, and snippets.

@Floofies
Created March 28, 2020 12:33
Show Gist options
  • Save Floofies/a9f2f9bb0f76fa6e8959f52da4667df6 to your computer and use it in GitHub Desktop.
Save Floofies/a9f2f9bb0f76fa6e8959f52da4667df6 to your computer and use it in GitHub Desktop.
const Hz = require("hertzscript-vm");
const performance = require("perf_hooks").performance;
// Lazy Caterer's Sequence
const src1 = `
var total = 1;
const numbers = [1];
while (total < 200) {
numbers.push(numbers[numbers.length - 1] + total);
total++;
}
console.log('Generated ' + numbers.length + ' numbers');
`;
const ctx = new Hz.Context(new Hz.VirtualMachine());
const cTimings = [];
const fTimings = [];
var cStart;
var fStart;
var total = 0;
const trace = [];
function addTrace(str) {
trace.unshift(str);
if (trace.length > 20) trace.pop();
}
ctx.reflector.hook.before.call((rValue, stop, tokenLib, state) => {
addTrace(state.functor.name + "();");
});
ctx.reflector.hook.before.callArgs((rValue, stop, tokenLib, state) => {
addTrace(state.functor.name + "(" + state.args.join(", ") + ");");
});
ctx.reflector.hook.before.callMethod((rValue, stop, tokenLib, state) => {
if (typeof state.object.constructor.name === "string") {
var name = state.object.constructor.name;
} else if (typeof state.object.name === "string") {
var name = state.object.name;
} else {
var name = typeof state.object;
}
if (typeof state.property === "string") {
var prop = state.property;
} else {
var prop = state.property.toString();
}
addTrace(name + "." + prop + "();");
});
ctx.reflector.hook.before.callMethodArgs((rValue, stop, tokenLib, state) => {
const name = (typeof state.object.constructor.name === "string") ? state.object.constructor.name : state.object.name;
addTrace(name + "." + state.property + "(" + state.args.join(", ") + ");");
});
ctx.reflector.hook.before.return((rValue, stop, tokenLib, state) => {
addTrace("return;");
});
ctx.reflector.hook.before.returnValue((rValue, stop, tokenLib, state) => {
addTrace("return " + state.arg + ";");
});
ctx.reflector.hook.before.cycle(() => {
cStart = performance.now();
});
ctx.reflector.hook.after.cycle(() => {
cTimings.push(performance.now() - cStart);
});
ctx.reflector.hook.before.execute(() => {
fStart = performance.now();
});
ctx.reflector.hook.after.execute(() => {
fTimings.push(performance.now() - fStart);
});
ctx.importString(src1, true);
ctx.runComplete();
var cTotal = 0;
for (const time of cTimings) {
cTotal += time;
}
var fTotal = 0;
for (const time of fTimings) {
fTotal += time;
}
console.log("Total Cycle Time: " + cTotal + "ms");
console.log("Average Cycle Time: " + (cTotal / cTimings.length) + "ms");
console.log("Total Userspace Time: " + fTotal + "ms");
console.log("Average Userspace Time: " + (fTotal / fTimings.length) + "ms");
console.log("Instruction Trace:");
console.log(trace.join("\n"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment