Skip to content

Instantly share code, notes, and snippets.

@Radon8472
Created February 22, 2024 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Radon8472/1d2d23a00e0b5084df446da97205c116 to your computer and use it in GitHub Desktop.
Save Radon8472/1d2d23a00e0b5084df446da97205c116 to your computer and use it in GitHub Desktop.
A class to benchmark run duration of functions
/**
* 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