github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bench/vm/vm_test.go (about)

     1  package main
     2  
     3  import "testing"
     4  
     5  type InstructionSet interface {
     6  	Advance(vm *VM)
     7  	Stop(vm *VM)
     8  }
     9  
    10  type VM struct {
    11  	IP     int
    12  	Memory [1 << 14]byte
    13  }
    14  
    15  type CPUDirect struct{}
    16  
    17  func (cpu *CPUDirect) Advance(vm *VM) { vm.IP++ }
    18  func (cpu *CPUDirect) Stop(vm *VM)    { vm.IP++ }
    19  
    20  func BenchmarkDirect(b *testing.B) {
    21  	vm := &VM{}
    22  	cpu := &CPUDirect{}
    23  	for i := 0; i < b.N; i++ {
    24  		cpu.Advance(vm)
    25  		cpu.Stop(vm)
    26  		cpu.Advance(vm)
    27  		cpu.Stop(vm)
    28  		cpu.Advance(vm)
    29  		cpu.Stop(vm)
    30  		cpu.Advance(vm)
    31  		cpu.Stop(vm)
    32  		cpu.Advance(vm)
    33  		cpu.Stop(vm)
    34  	}
    35  }
    36  
    37  type CPUInterface struct{}
    38  
    39  func (cpu *CPUInterface) Advance(vm *VM) { vm.IP++ }
    40  func (cpu *CPUInterface) Stop(vm *VM)    { vm.IP++ }
    41  
    42  func BenchmarkInterface(b *testing.B) {
    43  	var iset InstructionSet
    44  	vm := &VM{}
    45  	iset = &CPUInterface{}
    46  	for i := 0; i < b.N; i++ {
    47  		iset.Advance(vm)
    48  		iset.Stop(vm)
    49  		iset.Advance(vm)
    50  		iset.Stop(vm)
    51  		iset.Advance(vm)
    52  		iset.Stop(vm)
    53  		iset.Advance(vm)
    54  		iset.Stop(vm)
    55  		iset.Advance(vm)
    56  		iset.Stop(vm)
    57  	}
    58  }
    59  
    60  type CPUUnknown struct{}
    61  
    62  func (cpu *CPUUnknown) Advance(vm *VM) { vm.IP++ }
    63  func (cpu *CPUUnknown) Stop(vm *VM)    { vm.IP++ }
    64  
    65  func BenchmarkInterfaceUnknown(b *testing.B) {
    66  	var iset interface{}
    67  	vm := &VM{}
    68  	iset = &CPUUnknown{}
    69  	for i := 0; i < b.N; i++ {
    70  		iset.(InstructionSet).Advance(vm)
    71  		iset.(InstructionSet).Stop(vm)
    72  		iset.(InstructionSet).Advance(vm)
    73  		iset.(InstructionSet).Stop(vm)
    74  		iset.(InstructionSet).Advance(vm)
    75  		iset.(InstructionSet).Stop(vm)
    76  		iset.(InstructionSet).Advance(vm)
    77  		iset.(InstructionSet).Stop(vm)
    78  		iset.(InstructionSet).Advance(vm)
    79  		iset.(InstructionSet).Stop(vm)
    80  	}
    81  }