Benchmark.js
by wared
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/1.0.0/benchmark.min.js"></script>
<ul id='cycleResults'>
</ul>
<div id="result">
</div>
<br>
<button id="btn">
Run Tests
</button>
JavaScript
function range (first, last) {
var range = new Array(last - first + 1); range[0] = first;
for (var i = 1; range[i - 1] < last; i++) range[i] = first + i;
return range;
}
function test1()
{
range(1, 10);
}
function test2()
{
var length = 10; Array.from({ length }, (_, i) => i + 1);
}
var cycleResults = document.getElementById('cycleResults');
var result = document.getElementById('result');
var btn = document.getElementById('btn');
// BENCHMARK ====================
btn.onclick = function runTests(){
btn.setAttribute('disable', true);
cycleResults.innerHTML = '';
result.textContent = 'Tests running...';
var suite = new Benchmark.Suite;
// add tests
suite
.add('test1', test1)
.add('test2', test2)
// add listeners
.on('cycle', function(event) {
var result = document.createElement('li');
result.textContent = String(event.target);
document.getElementById('cycleResults')
.appendChild(result);
})
.on('complete', function() {
result.textContent = 'Fastest is ' + this.filter('fastest').pluck('name');
btn.setAttribute('disable', false);
})
// run async
.run({ 'async': true });
};