Created
February 22, 2024 09:06
-
-
Save Radon8472/1d2d23a00e0b5084df446da97205c116 to your computer and use it in GitHub Desktop.
A class to benchmark run duration of functions
This file contains hidden or 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
/** | |
* A class to benchmark (multiple) function calls | |
* | |
* @author Radon8472 | |
* @since 2024-02-22 | |
* @version 1.0 | |
* | |
* | |
* @example | |
* Speedtest.messure( | |
* function (a, b) { return a+b; }, | |
* 'benchmark_ab_function' | |
* ); | |
* | |
* console.log('Function calls took %d ms', Speedtest.times['benchmark_ab_function']) | |
* | |
*/ | |
class Speedtest { | |
/** | |
* @type {object} Stores summed times for each test (name given to "messure()" method is the key | |
*/ | |
static times = {}; | |
/** | |
* Messure times for a function-call and summarize it to `speedtest.times` for later usage | |
* | |
* @param {function} func A function whose time should be measured | |
* @param {string} name the name where this time should be counted to | |
* | |
* @returns {function(...[*]): *} A wrapper function, that acts the same way as the function given as "func"-argument | |
* | |
*/ | |
static messure (func, name = '_unnamed') { | |
return (...args) => { | |
if (!(name in this.times)) | |
this.times[name] = 0; | |
const start = performance.now(); | |
let result; | |
try { | |
result = func(...args); | |
} catch (error) { | |
console.error('Error in Speedtest', error); | |
} | |
this.times[name] += (performance.now() - start); | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment