gpujs / gpu.js

GPU Accelerated JavaScript
https://gpu.rocks
MIT License
15.12k stars 655 forks source link

Dirt simple implementation of clz32 #750

Open DragonForgedTheArtist opened 2 years ago

DragonForgedTheArtist commented 2 years ago

Not really an issue. Just thought I would help out a bit if I could. This is the same way you would implement this in hardware. You pretty much have to bit bang this to get the answer. In order to find the first zero bit of a number, you have to find the last non-zero bit and shift one.

const clz32 = gpu.createKernel(function(x) {
    let bits = 0;
    if(x === 0){
        return 32;
    }
    while(Math.pow(2,bits) <= x && bits < 32){
        bits+=1;
    }
    return 32-bits;
}).setOutput([1]);
DragonForgedTheArtist commented 2 years ago

Of course once I did some experiments, looked at the source and found out that bitwise operations were supported (not documented) this might be a hair bit more optimized

const clz32 = gpu.createKernel(function(x) {
    let bits = 0;
    let curbit = 1;
    if(x === 0){
        return 32;
    }
    while(curbit <= x && bits < 32){
        curbit =curbit << 1;
        bits+=1;
    }
    return 32-bits;
}).setOutput([1]);