LuaJIT-to-Go/bench/sandbox_bench_test.go
2025-03-27 21:51:31 -05:00

134 lines
2.8 KiB
Go

package luajit_bench
import (
"testing"
luajit "git.sharkk.net/Sky/LuaJIT-to-Go"
)
// BenchmarkSandboxLuaExecution measures the performance of executing raw Lua code
func BenchmarkSandboxLuaExecution(b *testing.B) {
sandbox := luajit.NewSandbox()
defer sandbox.Close()
// Simple Lua code that does some computation
code := `
local sum = 0
for i = 1, 100 do
sum = sum + i
end
return sum
`
b.ResetTimer()
for i := 0; i < b.N; i++ {
result, err := sandbox.Run(code)
if err != nil {
b.Fatalf("Failed to run code: %v", err)
}
if result != float64(5050) {
b.Fatalf("Incorrect result: %v", result)
}
}
}
// BenchmarkSandboxBytecodeExecution measures the performance of executing precompiled bytecode
func BenchmarkSandboxBytecodeExecution(b *testing.B) {
sandbox := luajit.NewSandbox()
defer sandbox.Close()
// Same code as above, but precompiled
code := `
local sum = 0
for i = 1, 100 do
sum = sum + i
end
return sum
`
// Compile the bytecode once
bytecode, err := sandbox.Compile(code)
if err != nil {
b.Fatalf("Failed to compile bytecode: %v", err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
result, err := sandbox.RunBytecode(bytecode)
if err != nil {
b.Fatalf("Failed to run bytecode: %v", err)
}
if result != float64(5050) {
b.Fatalf("Incorrect result: %v", result)
}
}
}
// BenchmarkSandboxComplexComputation measures performance with more complex computation
func BenchmarkSandboxComplexComputation(b *testing.B) {
sandbox := luajit.NewSandbox()
defer sandbox.Close()
// More complex Lua code that calculates Fibonacci numbers
code := `
function fibonacci(n)
if n <= 1 then
return n
end
return fibonacci(n-1) + fibonacci(n-2)
end
return fibonacci(15) -- Not too high to avoid excessive runtime
`
b.ResetTimer()
for i := 0; i < b.N; i++ {
result, err := sandbox.Run(code)
if err != nil {
b.Fatalf("Failed to run code: %v", err)
}
if result != float64(610) {
b.Fatalf("Incorrect result: %v", result)
}
}
}
// BenchmarkSandboxFunctionCall measures performance of calling a registered Go function
func BenchmarkSandboxFunctionCall(b *testing.B) {
sandbox := luajit.NewSandbox()
defer sandbox.Close()
// Register a simple addition function
add := func(s *luajit.State) int {
a := s.ToNumber(1)
b := s.ToNumber(2)
s.PushNumber(a + b)
return 1
}
err := sandbox.RegisterFunction("add", add)
if err != nil {
b.Fatalf("Failed to register function: %v", err)
}
// Lua code that calls the Go function in a loop
code := `
local sum = 0
for i = 1, 100 do
sum = add(sum, i)
end
return sum
`
b.ResetTimer()
for i := 0; i < b.N; i++ {
result, err := sandbox.Run(code)
if err != nil {
b.Fatalf("Failed to run code: %v", err)
}
if result != float64(5050) {
b.Fatalf("Incorrect result: %v", result)
}
}
}