xxxxxxxxxx
95
/*
Simple code for microbenchmarking.
Currently just tinkering.
For a more robust and feature-rich solution,
there are libraries like tinybench:
https://github.com/tinylibs/tinybench
Notes about the code:
The `executionTimes()` API makes `count` required;
might be good for it to be optional with a default
value. (Currently, it can't be the last parameter
since I'm using a rest parameter.)
For small tasks, times may round to zero.
Might consider returning total time instead.
Or, could have a separate function or mode
for returning total time.
It may be preferable sometimes to allow user
to specify an amount of time during which the
function will continue to be called.
What about randomizing inputs? Could that be
easier? When might that be helpful?
To-do: Maybe implement some more statistics
for analyzing the data, like percentiles?
*/
// For `count` iterations, call `func` with given `input`,
// and return an array of the execution times in milliseconds
function executionTimes(count, func, input) {
let startTime, endTime;
let times = [];
for (let i = 0; i < count; i++) {
startTime = performance.now();
func(input);
endTime = performance.now();
times.push(endTime - startTime);
}
return times;
}
// Find min of array
// (a simple function to benchmark, for testing)
function min(arr) {
let currentMin = arr[0];
for (let i = 0; i < arr.length; i++) {
if (arr[i] < currentMin) {
currentMin = arr[i];
}
}
return currentMin;
}
// Generate random integer from 1, ... , `max`
// (helper for generating test data)
function randomInt(max) {
return Math.ceil(max * Math.random());
}
// Generate array of length `count`,
// filled with random integers from 1, ... , `max`
// (for generating test data)
function randomInts(max, count) {
let ints = [];
for (let i = 0; i < count; i++) {
ints.push(randomInt(max));
}
return ints;
}
// Arithmetic mean (average) of values
function mean(values) {
let sum = 0;
for (let i = 0; i < values.length; i++) {
sum += values[i];
}
return sum / values.length;
}
// Tests
// The input size to the function being tested is `intCount`.
// Try changing its value and observe what happens to the mean
// execution time!
let intMax = 1000;
let intCount = 100000;
let executionCount = 1000;
let input = randomInts(intMax, intCount);
let times = executionTimes(executionCount, min, input);
console.log(mean(times));