repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/skills/benchmark-lua/SKILL.md

Raw

name: benchmark-lua description: Write Lua benchmarks using os.clock and LuaJIT profiler. Use when: user wants to benchmark Lua code, measure LuaJIT performance, optimize Lua scripts, or profile Lua applications. license: MIT

Lua Benchmarking

This skill covers benchmarking Lua/LuaJIT code using manual timing and built-in profiling tools.

Timing Basics

os.clock

local function benchmark(fn, iterations)
    -- Warmup: allow JIT to compile
    for i = 1, 10000 do
        fn()
    end

    -- Measure
    local start = os.clock()
    for i = 1, iterations do
        fn()
    end
    local elapsed = os.clock() - start

    local ns_per_op = (elapsed * 1e9) / iterations
    print(string.format("%.2f ns/op", ns_per_op))
end

socket.gettime (Higher Resolution)

local socket = require("socket")

local function time_it(fn, iterations)
    local start = socket.gettime()
    for i = 1, iterations do
        fn()
    end
    local elapsed = socket.gettime() - start
    return elapsed / iterations
end

Writing Benchmarks

Basic Pattern

local function fibonacci(n)
    if n < 2 then return n end
    return fibonacci(n - 1) + fibonacci(n - 2)
end

local function run_benchmark(name, fn, iterations)
    -- Warmup
    for i = 1, 5000 do
        fn()
    end

    -- Benchmark
    local start = os.clock()
    for i = 1, iterations do
        fn()
    end
    local elapsed = os.clock() - start

    local ns_per_op = (elapsed * 1e9) / iterations
    print(string.format("%s: %.2f ns/op", name, ns_per_op))
end

-- Run
run_benchmark("fibonacci(20)", function()
    return fibonacci(20)
end, 1000)

Avoiding Dead Code Elimination

LuaJIT is aggressive about DCE. Ensure results are used:

-- BAD: result may be optimized away
local function bench_bad()
    expensive_computation()
end

-- GOOD: result is used
local function bench_good()
    local result = expensive_computation()
    return result  -- or use in calculation
end

-- Also good: prevent DCE by "using" result
local sum = 0
local function bench_with_sink()
    local result = expensive_computation()
    sum = sum + result  -- result is used
end

Benchmark Wrapper Function

local function benchmark(name, fn, iterations)
    iterations = iterations or 1000

    -- JIT warmup: run enough times to trigger compilation
    for i = 1, 10000 do
        fn()
    end

    -- Actual measurement
    local start = os.clock()
    for i = 1, iterations do
        fn()
    end
    local elapsed = os.clock() - start

    local per_op = (elapsed * 1e9) / iterations
    local per_sec = iterations / elapsed

    print(string.format("%s:", name))
    print(string.format("  %.2f ns/op", per_op))
    print(string.format("  %.0f ops/sec", per_sec))
end

LuaJIT Profiler

Command Line

# Basic profiling
luajit -jp myscript.lua

# To file
luajit -jp=profile.log myscript.lua

# Flamegraph
luajit -jp=flamegraph,profile.log myscript.lua

# Safe mode (lower overhead)
luajit -jp=safe myscript.lua

Profiler Options

Option Description
-jp Enable profiler
-jp=file Output to file
-jp=safe Lower overhead
-jp=flamegraph Generate flamegraph data
-jp=exit Profile until exit

In-Code Profiling

local jit = require("jit")

-- Start
jit.p.start()

-- Your code
for i = 1, 10000 do
    do_work()
end

-- Stop and dump
jit.p.stop()
jit.p.dump()  -- or use file: jit.p.dump(file)

Debug Hooks (Alternative Profiler)

For when you need more control:

local function profile(fn)
    local info = {}
    local start_time = os.clock()

    local function hook(event)
        local d = debug.getinfo(2, "nS")
        local key = (d.name or "unknown") .. ":" .. (d.linedefined or 0)
        info[key] = (info[key] or 0) + 1
    end

    debug.sethook(hook, "c")

    fn()

    debug.sethook()

    -- Print results
    local sorted = {}
    for k, v in pairs(info) do
        table.insert(sorted, {key = k, count = v})
    end
    table.sort(sorted, function(a, b) return a.count > b.count end)

    print("Profile:")
    for i = 1, math.min(20, #sorted) do
        print(string.format("  %s: %d", sorted[i].key, sorted[i].count))
    end
end

LuaJIT vs Lua 5.x

Key Differences

Checking Which Engine

print(_VERSION)  -- Lua 5.1 or LuaJIT

-- Check JIT availability
if jit then
    print("JIT enabled")
    print(jit.version)
end

Common Pitfalls

  1. Warmup is essential - LuaJIT needs 1000+ iterations to compile hot code
  2. First run is slow - Measures interpreted, not JITted code
  3. DCE - Ensure results are used, or LuaJIT optimizes them away
  4. Small functions - Very small functions may inline away
  5. Table allocation - Creating tables in loops is expensive
  6. String concatenation - Use table.concat instead of .. in loops

Quick Reference

Task Command/Pattern
Time a function os.clock() loop
Profiler luajit -jp script.lua
To file luajit -jp=profile.log script.lua
Flamegraph luajit -jp=flamegraph script.lua
Check JIT if jit then ... end
Prevent DCE Use result in calculation

Example: Comparing Implementations

local function fib_recursive(n)
    if n < 2 then return n end
    return fib_recursive(n - 1) + fib_recursive(n - 2)
end

local function fib_iterative(n)
    if n < 2 then return n end
    local a, b = 0, 1
    for i = 2, n do
        a, b = b, a + b
    end
    return b
end

print("Comparing fibonacci(25):")
benchmark("recursive", function() return fib_recursive(25) end, 100)
benchmark("iterative", function() return fib_iterative(25) end, 10000)
Markdown source
File outline
---
name: benchmark-lua
description: Write Lua benchmarks using os.clock and LuaJIT profiler. Use when: user wants to benchmark Lua code, measure LuaJIT performance, optimize Lua scripts, or profile Lua applications.
license: MIT
---

# Lua Benchmarking

This skill covers benchmarking Lua/LuaJIT code using manual timing and built-in
profiling tools.

## Timing Basics

### os.clock

```lua
local function benchmark(fn, iterations)
    -- Warmup: allow JIT to compile
    for i = 1, 10000 do
        fn()
    end

    -- Measure
    local start = os.clock()
    for i = 1, iterations do
        fn()
    end
    local elapsed = os.clock() - start

    local ns_per_op = (elapsed * 1e9) / iterations
    print(string.format("%.2f ns/op", ns_per_op))
end
```

### socket.gettime (Higher Resolution)

```lua
local socket = require("socket")

local function time_it(fn, iterations)
    local start = socket.gettime()
    for i = 1, iterations do
        fn()
    end
    local elapsed = socket.gettime() - start
    return elapsed / iterations
end
```

## Writing Benchmarks

### Basic Pattern

```lua
local function fibonacci(n)
    if n < 2 then return n end
    return fibonacci(n - 1) + fibonacci(n - 2)
end

local function run_benchmark(name, fn, iterations)
    -- Warmup
    for i = 1, 5000 do
        fn()
    end

    -- Benchmark
    local start = os.clock()
    for i = 1, iterations do
        fn()
    end
    local elapsed = os.clock() - start

    local ns_per_op = (elapsed * 1e9) / iterations
    print(string.format("%s: %.2f ns/op", name, ns_per_op))
end

-- Run
run_benchmark("fibonacci(20)", function()
    return fibonacci(20)
end, 1000)
```

### Avoiding Dead Code Elimination

LuaJIT is aggressive about DCE. Ensure results are used:

```lua
-- BAD: result may be optimized away
local function bench_bad()
    expensive_computation()
end

-- GOOD: result is used
local function bench_good()
    local result = expensive_computation()
    return result  -- or use in calculation
end

-- Also good: prevent DCE by "using" result
local sum = 0
local function bench_with_sink()
    local result = expensive_computation()
    sum = sum + result  -- result is used
end
```

### Benchmark Wrapper Function

```lua
local function benchmark(name, fn, iterations)
    iterations = iterations or 1000

    -- JIT warmup: run enough times to trigger compilation
    for i = 1, 10000 do
        fn()
    end

    -- Actual measurement
    local start = os.clock()
    for i = 1, iterations do
        fn()
    end
    local elapsed = os.clock() - start

    local per_op = (elapsed * 1e9) / iterations
    local per_sec = iterations / elapsed

    print(string.format("%s:", name))
    print(string.format("  %.2f ns/op", per_op))
    print(string.format("  %.0f ops/sec", per_sec))
end
```

## LuaJIT Profiler

### Command Line

```bash
# Basic profiling
luajit -jp myscript.lua

# To file
luajit -jp=profile.log myscript.lua

# Flamegraph
luajit -jp=flamegraph,profile.log myscript.lua

# Safe mode (lower overhead)
luajit -jp=safe myscript.lua
```

### Profiler Options

| Option           | Description              |
| ---------------- | ------------------------ |
| `-jp`            | Enable profiler          |
| `-jp=file`       | Output to file           |
| `-jp=safe`       | Lower overhead           |
| `-jp=flamegraph` | Generate flamegraph data |
| `-jp=exit`       | Profile until exit       |

### In-Code Profiling

```lua
local jit = require("jit")

-- Start
jit.p.start()

-- Your code
for i = 1, 10000 do
    do_work()
end

-- Stop and dump
jit.p.stop()
jit.p.dump()  -- or use file: jit.p.dump(file)
```

## Debug Hooks (Alternative Profiler)

For when you need more control:

```lua
local function profile(fn)
    local info = {}
    local start_time = os.clock()

    local function hook(event)
        local d = debug.getinfo(2, "nS")
        local key = (d.name or "unknown") .. ":" .. (d.linedefined or 0)
        info[key] = (info[key] or 0) + 1
    end

    debug.sethook(hook, "c")

    fn()

    debug.sethook()

    -- Print results
    local sorted = {}
    for k, v in pairs(info) do
        table.insert(sorted, {key = k, count = v})
    end
    table.sort(sorted, function(a, b) return a.count > b.count end)

    print("Profile:")
    for i = 1, math.min(20, #sorted) do
        print(string.format("  %s: %d", sorted[i].key, sorted[i].count))
    end
end
```

## LuaJIT vs Lua 5.x

### Key Differences

- **LuaJIT**: Has JIT compiler, much faster for hot loops
- **Lua 5.x**: Interpreter only, consistent but slower
- **Warmup**: LuaJIT needs warmup iterations for JIT compilation

### Checking Which Engine

```lua
print(_VERSION)  -- Lua 5.1 or LuaJIT

-- Check JIT availability
if jit then
    print("JIT enabled")
    print(jit.version)
end
```

## Common Pitfalls

1. **Warmup is essential** - LuaJIT needs 1000+ iterations to compile hot code
2. **First run is slow** - Measures interpreted, not JITted code
3. **DCE** - Ensure results are used, or LuaJIT optimizes them away
4. **Small functions** - Very small functions may inline away
5. **Table allocation** - Creating tables in loops is expensive
6. **String concatenation** - Use table.concat instead of `..` in loops

## Quick Reference

| Task            | Command/Pattern                     |
| --------------- | ----------------------------------- |
| Time a function | `os.clock()` loop                   |
| Profiler        | `luajit -jp script.lua`             |
| To file         | `luajit -jp=profile.log script.lua` |
| Flamegraph      | `luajit -jp=flamegraph script.lua`  |
| Check JIT       | `if jit then ... end`               |
| Prevent DCE     | Use result in calculation           |

## Example: Comparing Implementations

```lua
local function fib_recursive(n)
    if n < 2 then return n end
    return fib_recursive(n - 1) + fib_recursive(n - 2)
end

local function fib_iterative(n)
    if n < 2 then return n end
    local a, b = 0, 1
    for i = 2, n do
        a, b = b, a + b
    end
    return b
end

print("Comparing fibonacci(25):")
benchmark("recursive", function() return fib_recursive(25) end, 100)
benchmark("iterative", function() return fib_iterative(25) end, 10000)
```