-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a benchmark to make sure an array inclusion check is beneficial.
- Loading branch information
Showing
4 changed files
with
53 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
// @ts-ignore | ||
import Benchmark = require('benchmark'); | ||
import {PRIMES, isPrime} from '../primes'; | ||
|
||
function withoutInclusionCheck(n: number) { | ||
if (!Number.isInteger(n) || n < 2) { | ||
return false; | ||
} | ||
if (n > 62837328) { | ||
throw new Error('Prime check only implemented up to 62837328'); | ||
} | ||
for (const prime of PRIMES) { | ||
if (prime * prime > n) { | ||
return true; | ||
} | ||
if (n % prime === 0) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
} | ||
|
||
function randSmallInt() { | ||
return Math.floor(Math.random() * 10000); | ||
} | ||
|
||
const primalityCheckSuite = new Benchmark.Suite(); | ||
primalityCheckSuite | ||
.add('primality check (with array inclusion)', () => isPrime(randSmallInt())) | ||
.add('primality check (without array inclusion)', () => | ||
withoutInclusionCheck(randSmallInt()) | ||
) | ||
.on('cycle', (event: {target: any}) => { | ||
console.log(String(event.target)); | ||
}) | ||
.on('complete', () => { | ||
console.log( | ||
'Fastest is ' + primalityCheckSuite.filter('fastest').map('name') | ||
); | ||
}) | ||
.run({async: true}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters