Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(value + 0.5) << 0 might actually be slightly faster, and is more accurate #27

Open
jeffpeck10x opened this issue Oct 14, 2021 · 1 comment

Comments

@jeffpeck10x
Copy link

For the round function, I noticed that you use 0.49, which seems to give a speed boost in some circumstances, but with random numbers, apparently not.

function createRandom(count, scale) {
  const a = new Float64Array(count);
  for (let i = 0; i < count; i++) {
    a[i] = Math.random() * scale;
  }
  return a;
}

function roundA(a, b) {
  for (let i = 0; i < a.length; i++) {
    b[i] = (a[i] + 0.49) << 0;
  }
}

function roundB(a, b) {
  for (let i = 0; i < a.length; i++) {
    b[i] = (a[i] + 0.5) << 0;
  }
}

function trunc(a, b) {
  for (let i = 0; i < a.length; i++) {
    b[i] = a[i] << 0;
  }
}

function main() {
  const a = createRandom(100000000, 1000);
  const b = new Int32Array(a.length);
  console.time("roundA");
  roundA(a, b);
  console.timeEnd("roundA");
  console.time("roundB");
  roundB(a, b);
  console.timeEnd("roundB");
  console.time("trunc");
  trunc(a, b);
  console.timeEnd("trunc");
  console.time("roundA");
  roundA(a, b);
  console.timeEnd("roundA");
  console.time("roundB");
  roundB(a, b);
  console.timeEnd("roundB");
  console.time("trunc");
  trunc(a, b);
  console.timeEnd("trunc");
}

main();
roundA: 301.97607421875 ms
roundB: 184.259033203125 ms
trunc: 179.185791015625 ms
roundA: 177.18603515625 ms
roundB: 179.783935546875 ms
trunc: 178.2119140625 ms
@ytiurin
Copy link
Owner

ytiurin commented Oct 17, 2021

Sure thing!
I picked .49 value to increase an accuracy:

assuming that input value range:

  • from 0.0 to 0.5 should result 0
  • from 0.51 to 1 should result 1

This will still give inacurate result for input value 0.501, but in context of color value - slight color shift might not be noticable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants