From 27ea13401dfa443243d588c5636c85e1037b986d Mon Sep 17 00:00:00 2001 From: Uri Shaked Date: Sun, 1 Dec 2019 23:18:22 +0200 Subject: feat: improve benchmark code compare 3 alternatives: 1. Current avrInstruction() implementation 2. Map opcodes using a Javascript map 3. Map opcodes using a Uint16Array and big switch statement --- benchmark/index.ts | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) (limited to 'benchmark/index.ts') diff --git a/benchmark/index.ts b/benchmark/index.ts index b90b6bd..02eee8d 100644 --- a/benchmark/index.ts +++ b/benchmark/index.ts @@ -1,31 +1,41 @@ -import { CPU } from '../src/cpu'; +import { CPU, ICPU } from '../src/cpu'; import { avrInstruction } from '../src/instruction'; import { createBenchmark } from './benchmark'; -import { instLDY } from './instruction-fn'; +import { permutations } from './permutations'; +import { instructions, executeInstruction } from './instruction-fn'; /* Approach 1: use large Uint16Array with all possible opcodes */ -const instructionMap = new Uint16Array(65536); -instructionMap[0x8088] = 0x5; +const instructionArray = new Uint16Array(65536); +for (let i = 0; i < instructions.length; i++) { + const { pattern } = instructions[i]; + for (const opcode of permutations(pattern.replace(/ /g, '').substr(0, 16))) { + if (!instructionArray[opcode]) { + instructionArray[opcode] = i + 1; + } + } +} function avrInstructionUintArray(cpu: CPU) { const opcode = cpu.progMem[cpu.pc]; - const mapped = instructionMap[opcode]; - switch (mapped) { - case 5: - instLDY(cpu, opcode); - break; - } + executeInstruction(instructionArray[opcode], cpu, opcode); } -/* Approach 1: use Map() */ -const objMap = new Map void>(); -objMap.set(0x8088, instLDY); +/* Approach 2: use instMap */ +const instructionMap: { [key: number]: (cpu: ICPU, opcode: number) => void } = {}; +for (const { pattern, fn } of instructions) { + for (const opcode of permutations(pattern.replace(/ /g, '').substr(0, 16))) { + if (!instructionMap[opcode]) { + instructionMap[opcode] = fn; + } + } +} function avrInstructionObjMap(cpu: CPU) { const opcode = cpu.progMem[cpu.pc]; - objMap.get(cpu.progMem[cpu.pc])(cpu, opcode); + instructionMap[opcode](cpu, opcode); } +/* Run the benchmark */ function run() { const benchmark = createBenchmark('cpu-benchmark'); -- cgit v1.2.3