Benchmark.js ちゃんと使えるので良いのですが、計測を頑張っている割に結果表示が貧弱というのが悲しいところです。

なので Perl の Benchmark.pm 風に表示する complete の関数を書いてみました。cli-table に依存します。

for x 115,102,309 ops/sec ±0.43% (95 runs sampled)
for of x 62,020,029 ops/sec ±0.23% (96 runs sampled)
Fastest is for
+--------+-------------------------------+--------+-----------+
| name   | ops                           | vs for | vs for of |
+--------+-------------------------------+--------+-----------+
| for    | 115102308.6ops/sec (+/-0.43%) | -      | 86%       |
+--------+-------------------------------+--------+-----------+
| for of | 62020028.7ops/sec (+/-0.23%)  | -46%   | -         |
+--------+-------------------------------+--------+-----------+
//#!/usr/bin/env node

"use strict";

const Benchmark = require('benchmark');
const Table = require('cli-table');
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
new Benchmark.Suite().
	add('for', () => {
		let sum = 0;
		for (let i = 0, len = array.length; i < len; i++) {
			sum += array[i];
		}
		return sum;
	}).
	add('for of', () => {
		let sum = 0;
		for (let i of array) {
			sum += i;
		}
		return sum;
	}).
	on('cycle', function(event) {
		console.log(String(event.target));
	}).
	on('complete', function() {
		console.log('Fastest is ' + this.filter('fastest').map('name'));

		const array = this.slice(0).sort( (a, b) => b.hz - a.hz);
		const table = new Table({
			chars: {
				'top': '-' ,
				'top-mid': '+' ,
				'top-left': '+' ,
				'top-right': '+',
				'bottom': '-' ,
				'bottom-mid': '+' ,
				'bottom-left': '+' ,
				'bottom-right': '+',
				'left': '|' ,
				'left-mid': '+' ,
				'mid': '-' ,
				'mid-mid': '+',
				'right': '|' ,
				'right-mid': '+' ,
				'middle': '|'
			},
			head: ['name', 'ops'].concat( array.map( b => 'vs ' + b.name ) )
		});
		const comparison = array.map( (a, ia) => array.map( (b, ib) => {
			if (ia === ib) return "-";
			return Math.round((a.hz / b.hz - 1) * 100) + '%';
		}));
		array.forEach( (bench, i) => {
			table.push([
				bench.name,
				`${bench.hz.toFixed(1)}ops/sec (+/-${bench.stats.rme.toFixed(2)}%)`
			].concat(comparison[i]))
		});
		console.log(table.toString());
	}).
	run({});
  1. トップ
  2. tech
  3. Benchmark.js の結果表示を改善する