diff --git a/go.mod b/go.mod index 325ed06..fe37864 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module code.jmug.me/jmug/sqlite-wasm go 1.23.6 + +require github.com/tetratelabs/wazero v1.9.0 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..b0ddcac --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I= +github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM= diff --git a/main.go b/main.go new file mode 100644 index 0000000..09490f3 --- /dev/null +++ b/main.go @@ -0,0 +1,47 @@ +package main + +import ( + "context" + _ "embed" + "fmt" + "log" + "time" + + "github.com/tetratelabs/wazero" +) + +//go:embed testdata/zig-out/bin/addUpTo.wasm +var addUpToWasm []byte + +func main() { + ctx := context.Background() + + // Create a new WebAssembly Runtime. + r := wazero.NewRuntimeWithConfig(ctx, wazero.NewRuntimeConfig().WithCloseOnContextDone(true)) + defer r.Close(ctx) + + // Compile the Wasm binary once so that we can skip the entire compilation time during instantiation. + compiledWasm, err := r.CompileModule(ctx, addUpToWasm) + if err != nil { + log.Panicf("failed to compile Wasm binary: %v", err) + } + + start := time.Now() + for range 1000 { + // Instantiate a new Wasm module from the already compiled `compiledWasm`. + instance, err := r.InstantiateModule(ctx, compiledWasm, wazero.NewModuleConfig().WithName("")) + if err != nil { + log.Panicf("failed to instantiate %v", err) + } + + f := instance.ExportedFunction("addUpTo") + res, err := f.Call(ctx, 1000) + if err != nil { + log.Panicf("failed to call function: %v", err) + } else { + log.Printf("Got %d from wasm\n", res[0]) + } + } + end := time.Now() + fmt.Printf("Took %v to run functions\n", end.Sub(start)) +} diff --git a/testdata/build.zig b/testdata/build.zig index 283adb4..09fe24f 100644 --- a/testdata/build.zig +++ b/testdata/build.zig @@ -11,7 +11,7 @@ pub fn build(b: *std.Build) void { const add_up_to_mod = b.createModule(.{ .root_source_file = b.path("addupto.zig"), .target = wasmTarget, - .optimize = .ReleaseFast, + .optimize = .ReleaseSmall, }); const add_up_to_native_mod = b.createModule(.{ .root_source_file = b.path("addupto.zig"), diff --git a/testdata/zig-out/bin/addUpTo.wasm b/testdata/zig-out/bin/addUpTo.wasm index 6a90c8f..2dfcc5d 100755 Binary files a/testdata/zig-out/bin/addUpTo.wasm and b/testdata/zig-out/bin/addUpTo.wasm differ