negative modulo (v3)

Revision 3 of this benchmark created by Protronm on


Preparation HTML

<table id="tableRes"></table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
var dividends = [0, 1, 3, 16, -1, -3, -7, -47];
var divisors = [2, 5, 9];

function mmod(n, d) {
	return ((n % d) + d) % d;
}

function amod(n, d) {
    return n - (d * Math.floor(n / d));
}

function bmod(n, d) {
    var remain = n % d;
    return Math.floor(remain >= 0 ? remain : remain + d);
};

var cmod = function (n, m) {
    var remain = n % m;
    return remain >= 0 ? remain : remain + m;
};

var testFunction = function (f) {
    Benchmark.forEach(dividends, function (n) {
        Benchmark.forEach(divisors, function (d) {
            f(n, d);
        });
    });
};

var tableRes = $('#tableRes');

function addTableHeaders() {
    var firstTr = $('<tr>').appendTo(tableRes);
    $('<th>').text('dividend').appendTo(firstTr);
    $('<th>').text('divisor').appendTo(firstTr);
    ui.each(function(b) {
        $('<th>').text(b.name).appendTo(firstTr);
    });
}

function addTableData() {
    Benchmark.forEach(dividends, function (n) {
        Benchmark.forEach(divisors, function (d) {
            var tr = $('<tr>').appendTo(tableRes);
            $('<th>').text(n).appendTo(tr);
            $('<th>').text(d).appendTo(tr);
            var matchesFirst = true;
            var firstResult;
            ui.each(function(b) {
                fnName = b.fn.split('testFunction(')[1].split(');')[0];
                var result = eval(fnName + '(' + n + ',' + d + ')')
                if (!firstResult) {
                    firstResult = result;
                } else {
                    matchesFirst = firstResult === result;
                }
                $('<th>').text(result).addClass(matchesFirst ? 'matched' : 'unmatched').appendTo(tr);
            });
        });
    });
}

addTableHeaders();
addTableData();
</script>

<style>
.matched {
background-color: green;
}
.unmatched {
background-color: red;
}
</style>

Test runner

Ready to run.

Testing in
TestOps/sec
modulo m (% twice)
testFunction(mmod);
ready
modulo a (without %)
testFunction(amod);
ready
modulo b (% and ?)
testFunction(bmod);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.