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

希望能在运算效率上再加强 #53

Open
Midas-Li opened this issue Feb 15, 2023 · 1 comment
Open

希望能在运算效率上再加强 #53

Midas-Li opened this issue Feb 15, 2023 · 1 comment

Comments

@Midas-Li
Copy link

Midas-Li commented Feb 15, 2023

我做了一下压力测试,感觉效率上有改进的余地:

describe('求余数运算', () => {

//Math.round 用时14ms
it('test Math', () => {
let total=0;
for (let i = 1; i <= 10000 * 10; i++) {
total += Math.round(i * 100) / 100;
}
console.log(total);
});

//Math.round 再加上求精度,转浮点数,用时 273ms
it('test Math2', () => {
let total=0;
for (let i = 1; i <= 10000 * 10; i++) {
total += Math.round(parseFloat((i * 100).toPrecision(14))) / 100;
}
console.log(total);
});

//NP.round 用时1sec963ms
it('test NP', () => {
let total=0;
for (let i = 1; i <= 10000 * 10; i++) {
total += NP.round(i ,2) ;
}
console.log(total);
});
})

@Midas-Li
Copy link
Author

Midas-Li commented Feb 15, 2023

我利用空余时间也写了一个:
function extendNumDoubles(n: number, timesNum: number): number {
let s = n.toString();
let index = s.indexOf('.');
if (index === -1)
return Number(s + '0'.repeat(timesNum));
else {
let strLen = s.length;
let numPointPos = index + 1 + timesNum;

  let s2 =
        s.slice(0, index) +   //小数点前的数字
        s.slice(index + 1, numPointPos) +//原小数点后和新小数点前的数字
        (numPointPos <= strLen ? '.' : '') + //新小数点
        s.slice(numPointPos) +   //新小数点后的数字
        (numPointPos - strLen > 0 ? '0'.repeat(numPointPos - strLen) : '');  //补零
  
  return parseFloat(s2);
  
}

}

function toDecimalRound(x: number, digit: number): number {
digit = Math.abs(digit);
return Math.round(extendNumDoubles(Number(x.toPrecision(13)), digit)) / Math.pow(10, digit);
}

用了268ms的时间:
it('test Math toDecimalRound 268ms', () => {
let total = 0;
for (let i = 1; i <= 10000 * 10; i++) {
total += toDecimalRound(i,2);
}
console.log(total);
});

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

1 participant