Skip to content

Commit

Permalink
restructure, benchmarkjs added
Browse files Browse the repository at this point in the history
  • Loading branch information
nilshah98 committed Mar 29, 2019
1 parent 27cb8c7 commit 7ae525e
Show file tree
Hide file tree
Showing 11 changed files with 140 additions and 253 deletions.
8 changes: 0 additions & 8 deletions BENCHMARK.md

This file was deleted.

3 changes: 2 additions & 1 deletion ERRORS.md
@@ -1,3 +1,4 @@
- Difference between `var func = () => {}` v/s `var func = () => ()` v/s `var func = () => `.
- After a `Promise` is resolved, it cannot go back to pending state. More so, causing `Promise.all()` to execute for each single instance as well, now.
- Need to fill Array object before passing, else recieve something like - `<2 empty items>` in console.
- Need to fill Array object before passing, else recieve something like - `<2 empty items>` in console.
- Fixed relative path issues while exporting, use `__dirname` or other special variables like `__filename`
6 changes: 5 additions & 1 deletion NOTES.md
Expand Up @@ -10,4 +10,8 @@
- ArrayBuffer.transfer() method is still in experimental phase, so had to slice it, like polyfills would

# Array.forEach()
- Can't use a break statement in it
- Can't use a break statement in it

# Module Exports
- While requiring an exported module, the parser goes through the whole of required file, and executes everything, if a function is called, that will run
- Whereas only the exported ones are put into context
86 changes: 2 additions & 84 deletions array/index.js
@@ -1,12 +1,9 @@
const os = require("os");
const path = require("path");
const { Worker, parentPort, workerData } = require("worker_threads");
const inquirer = require("inquirer");
const ora = require("ora");

const cpuCount = os.cpus().length;
const workerPath = path.resolve("calcPrimes.js");
const NS_PER_SEC = 1e9;
const workerPath = path.resolve(__dirname + "/calcPrimes.js");

const calculatePrimes = number => {
return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -89,83 +86,4 @@ const calculatePrimes = number => {
});
};

const normalSieve = n => {
return new Promise((resolve, reject) => {
// Eratosthenes algorithm to find all primes under n
var array = [],
upperLimit = Math.sqrt(n),
output = [];

// Make an array from 2 to (n - 1)
for (var i = 0; i < n; i++) {
array.push(true);
}

// Remove multiples of primes starting from 2, 3, 5,...
for (var i = 2; i <= upperLimit; i++) {
if (array[i]) {
for (var j = i * i; j < n; j += i) {
array[j] = false;
}
}
}

// All array[i] set to true are primes
for (var i = 2; i < n; i++) {
if (array[i]) {
output.push(i);
}
}

resolve(output.length);
});
};

const calcTime = async (inp,func,label) => {
const spinner = ora("Calculating number of primes-").start();
const stTime = process.hrtime();
var res = await func(inp);
const endTime = process.hrtime(stTime);
spinner.succeed(`(${label}) Number of primes : ${res}`);
const time = endTime[0] * NS_PER_SEC + endTime[1];
spinner.stopAndPersist(
{
"text":`(${label}) Benchmark took : ${time} nanoseconds\n`,
"symbol":"⌛"
}
);
return time;
}

const run = async () => {
const { primeRange } = await inquirer.prompt([
{
type: "input",
name: "primeRange",
message: "Find primes till ?",
default: 100
}
]);

// Written using then
// calculatePrimes(primeRange).then((res) => {
// spinner.succeed(`Number of primes : ${res[0]}`)
// });

const workerTime = await calcTime(primeRange,calculatePrimes,"worker");
const localTime = await calcTime(primeRange,normalSieve,"main");
console.log(`⏱️ Time difference between worker and main thread : ${localTime-workerTime} nanoseconds`);
};


run();

/*
TODO =>
1. Analysis for SharedBufferArray v/s NormalArray
2. Recurring same process on worker thread after messaging mainThread
3. Message passing efficiency
3.1 Arrays
3.2 SharedArrayBuffers
3.3 Objects
*/
module.exports = calculatePrimes;
86 changes: 2 additions & 84 deletions arrayBuffer/index.js
@@ -1,12 +1,9 @@
const os = require("os");
const path = require("path");
const { Worker, parentPort, workerData } = require("worker_threads");
const inquirer = require("inquirer");
const ora = require("ora");

const cpuCount = os.cpus().length;
const workerPath = path.resolve("calcPrimes.js");
const NS_PER_SEC = 1e9;
const workerPath = path.resolve(__dirname + "/calcPrimes.js");

const calculatePrimes = number => {
return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -89,83 +86,4 @@ const calculatePrimes = number => {
});
};

const normalSieve = n => {
return new Promise((resolve, reject) => {
// Eratosthenes algorithm to find all primes under n
var array = [],
upperLimit = Math.sqrt(n),
output = [];

// Make an array from 2 to (n - 1)
for (var i = 0; i < n; i++) {
array.push(true);
}

// Remove multiples of primes starting from 2, 3, 5,...
for (var i = 2; i <= upperLimit; i++) {
if (array[i]) {
for (var j = i * i; j < n; j += i) {
array[j] = false;
}
}
}

// All array[i] set to true are primes
for (var i = 2; i < n; i++) {
if (array[i]) {
output.push(i);
}
}

resolve(output.length);
});
};

const calcTime = async (inp,func,label) => {
const spinner = ora("Calculating number of primes-").start();
const stTime = process.hrtime();
var res = await func(inp);
const endTime = process.hrtime(stTime);
spinner.succeed(`(${label}) Number of primes : ${res}`);
const time = endTime[0] * NS_PER_SEC + endTime[1];
spinner.stopAndPersist(
{
"text":`(${label}) Benchmark took : ${time} nanoseconds\n`,
"symbol":"⌛"
}
);
return time;
}

const run = async () => {
const { primeRange } = await inquirer.prompt([
{
type: "input",
name: "primeRange",
message: "Find primes till ?",
default: 100
}
]);

// Written using then
// calculatePrimes(primeRange).then((res) => {
// spinner.succeed(`Number of primes : ${res[0]}`)
// });

const workerTime = await calcTime(primeRange,calculatePrimes,"worker");
const localTime = await calcTime(primeRange,normalSieve,"main");
console.log(`⏱️ Time difference between worker and main thread : ${localTime-workerTime} nanoseconds`);
};


run();

/*
TODO =>
1. Analysis for SharedBufferArray v/s NormalArray
2. Recurring same process on worker thread after messaging mainThread
3. Message passing efficiency
3.1 Arrays
3.2 SharedArrayBuffers
3.3 Objects
*/
module.exports = calculatePrimes;
30 changes: 30 additions & 0 deletions benchmarking.js
@@ -0,0 +1,30 @@
const Benchmark = require('benchmark');
const suite = new Benchmark.Suite;
const sharedBufferPrime = require("./sharedArrayBuffer/main")



const inps = [100000000];
inps.forEach((num) => {

suite.add(String(num) + " test", {
defer: true,
fn: async (deferred) => {
await sharedBufferPrime.calcPrime(num);
deferred.resolve();
}
})
})

suite
// add listeners
.on('cycle', function(event) {
console.log(event.target.name);
console.log(event.target.stats.mean);
console.log(event.target.stats.sample.length);
})
.on('complete', function() {
// console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });
49 changes: 49 additions & 0 deletions index.js
@@ -0,0 +1,49 @@
const inquirer = require("inquirer");
const ora = require("ora");
const array = require("./array");
const arrayBuffer = require("./arrayBuffer");
const sharedArrayBuffer = require("./sharedArrayBuffer");
const normalSieve = require("./normalSieve");

const NS_PER_SEC = 1e9;

const calcTime = async (inp,func,label) => {
const spinner = ora("Calculating number of primes-").start();
const stTime = process.hrtime();
var res = await func(inp);
const endTime = process.hrtime(stTime);
spinner.succeed(`(${label}) Number of primes : ${res}`);
const time = endTime[0] * NS_PER_SEC + endTime[1];
spinner.stopAndPersist(
{
"text":`(${label}) Benchmark took : ${time} nanoseconds\n`,
"symbol":"⌛"
}
);
return time;
}

const run = async () => {
const { primeRange } = await inquirer.prompt([
{
type: "input",
name: "primeRange",
message: "Find primes till ?",
default: 100
}
]);

// Written using then
// calculatePrimes(primeRange).then((res) => {
// spinner.succeed(`Number of primes : ${res[0]}`)
// });

const workerArrayTime = await calcTime(primeRange,array,"worker array");
const workerArrayBufferTime = await calcTime(primeRange,arrayBuffer,"worker arrayBufer");
const workerSharedArrayBufferTime = await calcTime(primeRange,sharedArrayBuffer,"worker sharedArrayBuffer");
const localTime = await calcTime(primeRange,normalSieve,"main");
// console.log(`⏱️ Time difference between worker and main thread : ${localTime-workerTime} nanoseconds`);

};

run();
33 changes: 33 additions & 0 deletions normalSieve.js
@@ -0,0 +1,33 @@
const normalSieve = n => {
return new Promise((resolve, reject) => {
// Eratosthenes algorithm to find all primes under n
var array = [],
upperLimit = Math.sqrt(n),
output = [];

// Make an array from 2 to (n - 1)
for (var i = 0; i < n; i++) {
array.push(true);
}

// Remove multiples of primes starting from 2, 3, 5,...
for (var i = 2; i <= upperLimit; i++) {
if (array[i]) {
for (var j = i * i; j < n; j += i) {
array[j] = false;
}
}
}

// All array[i] set to true are primes
for (var i = 2; i < n; i++) {
if (array[i]) {
output.push(i);
}
}

resolve(output.length);
});
};

module.exports = normalSieve;
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Expand Up @@ -11,6 +11,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"benchmark": "^2.1.4",
"inquirer": "^6.2.2",
"ora": "^3.2.0"
}
Expand Down

0 comments on commit 7ae525e

Please sign in to comment.