LuaJIT-to-Go/bench/ezbench_test.go
2025-02-26 07:00:01 -06:00

134 lines
2.7 KiB
Go

package luajit_bench
import (
"testing"
luajit "git.sharkk.net/Sky/LuaJIT-to-Go"
)
var benchCases = []struct {
name string
code string
}{
{
name: "SimpleAddition",
code: `return 1 + 1`,
},
{
name: "LoopSum",
code: `
local sum = 0
for i = 1, 1000 do
sum = sum + i
end
return sum
`,
},
{
name: "FunctionCall",
code: `
local result = 0
for i = 1, 100 do
result = result + i
end
return result
`,
},
{
name: "TableCreation",
code: `
local t = {}
for i = 1, 100 do
t[i] = i * 2
end
return t[50]
`,
},
{
name: "StringOperations",
code: `
local s = "hello"
for i = 1, 10 do
s = s .. " world"
end
return #s
`,
},
}
func BenchmarkLuaDirectExecution(b *testing.B) {
for _, bc := range benchCases {
b.Run(bc.name, func(b *testing.B) {
L := luajit.New()
if L == nil {
b.Fatal("Failed to create Lua state")
}
defer L.Close()
defer L.Cleanup()
// First verify we can execute the code
if err := L.DoString(bc.code); err != nil {
b.Fatalf("Failed to execute test code: %v", err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
// Execute string and get results
nresults, err := L.Execute(bc.code)
if err != nil {
b.Fatalf("Failed to execute code: %v", err)
}
L.Pop(nresults) // Clean up any results
}
})
}
}
func BenchmarkLuaBytecodeExecution(b *testing.B) {
// First compile all bytecode
bytecodes := make(map[string][]byte)
for _, bc := range benchCases {
L := luajit.New()
if L == nil {
b.Fatal("Failed to create Lua state")
}
defer L.Cleanup()
bytecode, err := L.CompileBytecode(bc.code, bc.name)
if err != nil {
L.Close()
b.Fatalf("Error compiling bytecode for %s: %v", bc.name, err)
}
bytecodes[bc.name] = bytecode
L.Close()
}
for _, bc := range benchCases {
b.Run(bc.name, func(b *testing.B) {
L := luajit.New()
if L == nil {
b.Fatal("Failed to create Lua state")
}
defer L.Close()
defer L.Cleanup()
bytecode := bytecodes[bc.name]
// First verify we can execute the bytecode
if err := L.LoadAndRunBytecodeWithResults(bytecode, bc.name, 1); err != nil {
b.Fatalf("Failed to execute test bytecode: %v", err)
}
L.Pop(1) // Clean up the result
b.ResetTimer()
b.SetBytes(int64(len(bytecode))) // Track bytecode size in benchmarks
for i := 0; i < b.N; i++ {
if err := L.LoadAndRunBytecode(bytecode, bc.name); err != nil {
b.Fatalf("Error executing bytecode: %v", err)
}
}
})
}
}