commit 4a5b494f7c032252cccf0c75f429933ca3625f54 Author: Sven Slootweg Date: Tue Feb 15 18:28:08 2022 +0100 Initial commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..ffb76a8 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# time-call + +Measures the execution time of a chunk of code to nanosecond precision, while also providing access to its return value. + +Proper docs coming Eventually(tm), see example.js in the repo for now. diff --git a/example.js b/example.js new file mode 100644 index 0000000..a346368 --- /dev/null +++ b/example.js @@ -0,0 +1,17 @@ +"use strict"; + +const timeCall = require("./"); + +let dummyArray = new Array(20000).fill(0); + +let { value, time } = timeCall(() => { + for (let i = 0; i < 1e3; i++) { + dummyArray = dummyArray.map((value) => value + 1); + } + + return dummyArray; +}); + +console.log(time); // 386335402 +console.log(value); // [ 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, ... + \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..db17728 --- /dev/null +++ b/index.js @@ -0,0 +1,19 @@ +"use strict"; + +function hrtimeToNanoseconds(time) { + // If the numbers here become big enough to cause loss of precision, we probably have bigger issues than numeric precision... + return (time[0] * 1e9) + time[1]; +} + +module.exports = function measureTime(func) { + // let startTime = process.hrtime.bigint(); + let startTime = hrtimeToNanoseconds(process.hrtime()); + let result = func(); + // let endTime = process.hrtime.bigint(); + let endTime = hrtimeToNanoseconds(process.hrtime()); + + return { + value: result, + time: (endTime - startTime) + }; +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..5720f5f --- /dev/null +++ b/package.json @@ -0,0 +1,8 @@ +{ + "name": "time-call", + "version": "0.1.0", + "main": "index.js", + "repository": "https://git.cryto.net/joepie91/time-call.git", + "author": "Sven Slootweg ", + "license": "WTFPL OR CC0-1.0" +}