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 test1()
{
  for (var i = 0; i < 8; i++) (i & 14) >> 1
}

function test2()
{
  for (var i = 0; i < 8; i++) Math.floor(i / 2)
}

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 });
};