BUN-test/index.js
2025-01-05 18:01:24 +01:00

111 lines
1.8 KiB
JavaScript

import { cc, dlopen, FFIType } from "bun:ffi";
import source from "./matrixcc.c" with { type: "file"};
const {
symbols: { matrixcc },
} = cc({
source,
symbols: {
matrixcc: {
args: [],
returns: "int",
},
},
});
// Funzione JavaScript equivalente
function jsCC() {
const start = performance.now();
matrixcc();
const end = performance.now();
console.log(`TinyCC Execution Time: ${end - start}ms`);
}
// Funzione JavaScript equivalente
function jsTest() {
const start = performance.now();
matrixjs();
const end = performance.now();
console.log(`JavaScript Execution Time: ${end - start}ms`);
}
// Carica la libreria C
const path = `./bin/matrix.so`;
const { symbols } = dlopen(path, {
matrix: {
args: [], // La funzione C non prende argomenti
returns: FFIType.int, // La funzione C restituisce un intero
},
});
// Funzione per il test in C
function cTest() {
const start = performance.now();
// Chiama la funzione C per eseguire il test
symbols.matrix();
const end = performance.now();
console.log(`C Execution Time: ${end - start}ms`);
}
// test matrix
function matrixjs( n = 1500) {
let a = [];
let b = [];
let c = [];
for (let i = 0; i < n; i++) {
a[i] = [];
b[i] = [];
c[i] = [];
for (let j = 0; j < n; j++) {
a[i][j] = Math.floor(Math.random() * 100);
b[i][j] = Math.floor(Math.random() * 100);
c[i][j] = 0;
}
}
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
for (let k = 0; k < n; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
for (let i = 0; i < n; i++) {
a[i].length = 0;
b[i].length = 0;
c[i].length = 0;
}
a.length = 0;
b.length = 0;
c.length = 0;
}
// Avvia i test
jsCC();
jsTest();
cTest();