Created
August 20, 2022 18:50
-
-
Save bwasti/58996256308e646947d7b77f21e4b304 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// g++ ptr_test.cc --shared -o ptr_test.so | |
#include <cstdint> | |
static uint32_t g_p = 0; | |
extern "C" { | |
void* gen_ptr() { | |
return (void*)&g_p; | |
} | |
void digest_ptr(void* p) { | |
(*(uint32_t*)p) ++; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as ffi from "bun:ffi" | |
const link = ffi.dlopen("ptr_test.so", { | |
gen_ptr: { | |
returns: ffi.FFIType.ptr | |
}, | |
digest_ptr: { | |
args: [ffi.FFIType.ptr] | |
} | |
}) | |
const lib = link.symbols | |
function withToArrayBuffer() { | |
const p = lib.gen_ptr(); | |
const a = ffi.toArrayBuffer(p, 0, 1); | |
lib.digest_ptr(ffi.ptr(a)); | |
} | |
function withoutToArrayBuffer() { | |
const p = lib.gen_ptr(); | |
lib.digest_ptr(p); | |
} | |
for (let i = 0; i < 100000; ++i) { | |
withToArrayBuffer(); | |
withoutToArrayBuffer(); | |
} | |
const iters = 10000000; | |
{ | |
const t0 = performance.now(); | |
for (let i = 0; i < iters; ++i) { | |
withToArrayBuffer(); | |
} | |
const t1 = performance.now(); | |
console.log("toArrayBuffer", (t1-t0) * 1e6 / iters, "ns/iter"); | |
} | |
{ | |
const t0 = performance.now(); | |
for (let i = 0; i < iters; ++i) { | |
withoutToArrayBuffer(); | |
} | |
const t1 = performance.now(); | |
console.log("Without toArrayBuffer", (t1-t0) * 1e6 / iters, "ns/iter"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On a canary build, this is the output: