From 7ae525eca97a916df5bfe31016d4e6f645fed626 Mon Sep 17 00:00:00 2001 From: nilshah98 Date: Fri, 29 Mar 2019 20:02:26 +0530 Subject: [PATCH] restructure, benchmarkjs added --- BENCHMARK.md | 8 ---- ERRORS.md | 3 +- NOTES.md | 6 ++- array/index.js | 86 +------------------------------------- arrayBuffer/index.js | 86 +------------------------------------- benchmarking.js | 30 +++++++++++++ index.js | 49 ++++++++++++++++++++++ normalSieve.js | 33 +++++++++++++++ package-lock.json | 14 +++++++ package.json | 1 + sharedArrayBuffer/index.js | 77 +--------------------------------- 11 files changed, 140 insertions(+), 253 deletions(-) delete mode 100644 BENCHMARK.md create mode 100644 benchmarking.js create mode 100644 index.js create mode 100644 normalSieve.js diff --git a/BENCHMARK.md b/BENCHMARK.md deleted file mode 100644 index 13bc6cd..0000000 --- a/BENCHMARK.md +++ /dev/null @@ -1,8 +0,0 @@ -| Name | Inp | Time (in ms) | -|------|-----|------| -| array passing + promises + computation | 100 | 65 | -| array passing + promises + computation | 1000 | 80 | -| array passing + promises + computation | 10000 | 210 | -| array passing + promises + computation | 100000 | 3980 | -| array passing + computation | 100000 | 1570 | -| array passing + computation | 10000 | 110 | \ No newline at end of file diff --git a/ERRORS.md b/ERRORS.md index 56a0313..2478aa2 100644 --- a/ERRORS.md +++ b/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. \ No newline at end of file +- 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` \ No newline at end of file diff --git a/NOTES.md b/NOTES.md index 3b8c556..bcdaef2 100644 --- a/NOTES.md +++ b/NOTES.md @@ -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 \ No newline at end of file +- 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 \ No newline at end of file diff --git a/array/index.js b/array/index.js index 491d655..70b6bae 100644 --- a/array/index.js +++ b/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) => { @@ -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; \ No newline at end of file diff --git a/arrayBuffer/index.js b/arrayBuffer/index.js index 773bfb0..32a68f7 100644 --- a/arrayBuffer/index.js +++ b/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) => { @@ -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; \ No newline at end of file diff --git a/benchmarking.js b/benchmarking.js new file mode 100644 index 0000000..4131976 --- /dev/null +++ b/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 }); \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..2192c21 --- /dev/null +++ b/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(); \ No newline at end of file diff --git a/normalSieve.js b/normalSieve.js new file mode 100644 index 0000000..1a3b3c8 --- /dev/null +++ b/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; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index ad4f44e..067b138 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,6 +22,15 @@ "color-convert": "^1.9.0" } }, + "benchmark": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/benchmark/-/benchmark-2.1.4.tgz", + "integrity": "sha1-CfPeMckWQl1JjMLuVloOvzwqVik=", + "requires": { + "lodash": "^4.17.4", + "platform": "^1.3.3" + } + }, "chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", @@ -196,6 +205,11 @@ "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" }, + "platform": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.5.tgz", + "integrity": "sha512-TuvHS8AOIZNAlE77WUDiR4rySV/VMptyMfcfeoMgs4P8apaZM3JrnbzBiixKUv+XR6i+BXrQh8WAnjaSPFO65Q==" + }, "restore-cursor": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", diff --git a/package.json b/package.json index 1c133b4..26962da 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "author": "", "license": "ISC", "dependencies": { + "benchmark": "^2.1.4", "inquirer": "^6.2.2", "ora": "^3.2.0" } diff --git a/sharedArrayBuffer/index.js b/sharedArrayBuffer/index.js index 834ffdc..94785d1 100644 --- a/sharedArrayBuffer/index.js +++ b/sharedArrayBuffer/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) => { @@ -83,77 +80,7 @@ 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(); - +module.exports = calculatePrimes; /* TODO => 1. Analysis for SharedBufferArray v/s NormalArray