Created
January 29, 2012 22:19
-
-
Save skagedal/1701014 to your computer and use it in GitHub Desktop.
Speed testing and "fair coin" testing for pickRandom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> | |
<script src="underscore.js"></script> | |
<script type="text/javascript"> | |
function time(s, f) { | |
start = new Date(); | |
f(); | |
end = new Date(); | |
$("#speedtest").append(s + ": " + String(end - start) + " ms<br />"); | |
} | |
function testSpeed () { | |
var k = 10; | |
var n = 10000; | |
var times = 1000; | |
var a = _.range(n); | |
var b = _.range(n * 2); | |
time("picking with shuffle, size n", function () { | |
_.times(times, function () { _.first(_.shuffle(a), k); }); | |
}); | |
time("picking with shuffle, size n*2", function () { | |
_.times(times, function () { _.first(_.shuffle(b), k); }); | |
}); | |
time("picking with pickRandom, size n", function () { | |
_.times(times, function () { _.pickRandom(a, k); }); | |
}); | |
time("picking with pickRandom, size n*2", function () { | |
_.times(times, function () { _.pickRandom(b, k); }); | |
}); | |
$("#running").hide(); | |
} | |
COIN = {tosses: 0, heads: 0, coin: []}; | |
function initCoin() { | |
var i; | |
for (i = 0; i < 100; i++) { | |
COIN.coin.push(0); | |
} | |
for (i = 0; i < 100; i++) { | |
COIN.coin.push(1); | |
} | |
} | |
function testFairCoin() { | |
for (var i = 0; i < 10000; i++) { | |
pick = _.pickRandom(COIN.coin, COIN.coin.length / 2); | |
heads = _.reduce(pick, function (a, b) { return a + b; }, 0); | |
COIN.tosses += pick.length; | |
COIN.heads += heads; | |
} | |
$("#tosses").html(COIN.tosses); | |
$("#heads").html(COIN.heads); | |
$("#propo").html(COIN.heads / COIN.tosses); | |
} | |
function main() { | |
_.defer(testSpeed); | |
initCoin(); | |
$("#testcoin").click(testFairCoin); | |
} | |
$(main); | |
</script> | |
</head> | |
<body> | |
<p id="speedtest">Speed test <span id="running">(running)</span>:<br/> | |
<p><button id="testcoin">Test coin</button></p> | |
<p>Tosses: <span id="tosses"></span></p> | |
<p>Heads: <span id="heads"></span></p> | |
<p>Proportion: <span id="propo"></span></p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment