const gpu = new GPU();
// For reference
// This is the function to compute the J'th permutation
// of N elements. Rewrited to create the kernel.
function permutation(J, N) {
const arr = []
for(let i = 0; i < N; ++i)arr[i] = i;
let j = J;
for(let i = 2; i <= N; ++i){
let e1 = j % i;
const t = arr[e1];
arr[e1] = arr[i-1];
arr[i-1] = t;
j = (j - e1) / i;
}
return arr;
}
function permuteAt() {
const N = this.constants.length;
let I = N - this.thread.x - 1;
let J = this.thread.y;
for(let d = 0; d < N; ++d){
// check if the I'th element of the J'th permutation is d
let dPos = d;
let j = J;
let i = 0;
for(let i = 2; i <= N; ++i){
let e1 = j % i;
let e2 = i - 1;
// track the movements element d
if(e1 == dPos){
dPos = e2;
}else if(e2 == dPos){
dPos = e1;
}
j = (j - e1) / i;
}
// element d ended at position i
// console.log(JSON.stringify({dPos, I, J, N, t: this.thread}))
if(dPos == I){
return d;
}
}
return -1;
}
// Run it in javascript
let result;
const t0Js = Date.now()
for(let i = 0; i < 1000; ++i){
result = [0,1,2,3,4,5,6,7,8,9].map(v => permuteAt.apply({
thread: {x: i, y: v},
constants: {length: 10}
}))
}
const tfJs = Date.now();
console.log('time spend in javascript: ', (tfJs - t0Js)/10000);
const generatePermutations = gpu.createKernel(permuteAt).setOutput([10, 10000]).setConstants({length: 10});
const t0GPU = Date.now()
for(let i = 0; i < 100; ++i){
const c = generatePermutations();
}
const tfGPU = Date.now();
console.log('time spend in gpu: ', (tfGPU - t0GPU)/10000/100);
<script src="https://unpkg.com/gpu.js@latest/dist/gpu-browser.min.js"></script>