Skip to content

Instantly share code, notes, and snippets.

@hagino3000
Last active December 28, 2016 21:11
Show Gist options
  • Save hagino3000/5413975 to your computer and use it in GitHub Desktop.
Save hagino3000/5413975 to your computer and use it in GitHub Desktop.
asm.js sample
function fast_fib_module(stdlib, foreign, heap) {
"use asm";
function fib(n) {
n = n|0;
// nはint(符号の有無が不明の状態)
// 3はfixnum(0~2^31)
// 比較するためにnをシフト演算でunsignedに変換する
if (n >>> 0 < 3) {
return 1|0;
}
// fibの引数の型はintなのでintのサブセットであるsigned intで渡す
return (fib((n-1)|0) + fib((n-2)|0))|0;
}
return {
fib:fib
};
}
fast_fib = fast_fib_module(window).fib;
function slow_fib(n) {
if (n < 3) {
return 1;
}
return slow_fib(n-1) + slow_fib(n-2);
}
function fast_check(n) {
console.time("ASM:fib(" + n + ")");
console.log(fast_fib(n));
console.timeEnd("ASM:fib(" + n + ")");
}
function slow_check(n) {
console.time("NORMAL:fib(" + n + ")");
console.log(slow_fib(n));
console.timeEnd("NORMAL:fib(" + n + ")");
}
[01:40:15.035] fast_check(35)
[01:40:15.037] undefined
[01:40:15.037] ASM:fib(35): タイマー開始
[01:40:15.076] 9227465
[01:40:15.076] ASM:fib(35): 39ms
--
[01:40:21.539] slow_check(35)
[01:40:21.541] undefined
[01:40:21.541] NORMAL:fib(35): タイマー開始
[01:40:26.163] 9227465
[01:40:26.163] NORMAL:fib(35): 4622ms
@jkleiser
Copy link

jkleiser commented Feb 7, 2014

How do I use this in my browser? Do I need more than your fibonacci.js to see the effect of ASM? Do I have to use a special version of Firefox?

@jkleiser
Copy link

jkleiser commented Feb 7, 2014

When I try this i Firefox (27.0), I get this re. line 15: "TypeError: asm.js type error: non-expression-statement call must be coerced"
Does that explain why slow_check is faster than fast_check?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment