Übung 11 - WebAssembly
11.2 - Performanz-Messungen und -Vergleich
Bis 100.000 gibt es 9592 Primzahlen.
Benchmark
Against my expectations, the JavaScript variant is a lot faster than the WebAssembly variant. Since WASM is closer to the hardware and doesn't have to be interpreted, I expected it to be faster. However, unlike JavaScript, it can't apply improvements (while compiling).
Javascript
// based on stackoverflow answer from Ted Hopp https://stackoverflow.com/a/12287599/15212696
function countPrimes(max) {
let sieve = [], i, j;
let numbers=0;
for (i = 2; i <= max; ++i) {
if (!sieve[i]) {
numbers++;
for (j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
return numbers;
}
console.log(countPrimes(100000))
WAT Code
(module
(table 0 anyfunc)
(memory $0 1)
(export "memory" (memory $0))
(export "main" (func $main))
(func $main (; 0 ;) (result i32)
(local $0 i32)
(local $1 i32)
(local $2 i32)
(local $3 i32)
(local $4 i32)
(set_local $1
(i32.const 0)
)
(set_local $2
(i32.const 2)
)
(set_local $4
(i32.const 0)
)
(loop $label$0
(set_local $3
(i32.const 0)
)
(block $label$1
(loop $label$2
(set_local $0
(i32.add
(get_local $3)
(i32.const 2)
)
)
(block $label$3
(block $label$4
(br_if $label$4
(i32.ne
(get_local $1)
(get_local $3)
)
)
(set_local $4
(i32.add
(get_local $4)
(i32.const 1)
)
)
(br $label$3)
)
(br_if $label$1
(i32.eqz
(i32.rem_s
(get_local $2)
(get_local $0)
)
)
)
)
(set_local $3
(i32.add
(get_local $3)
(i32.const 1)
)
)
(br_if $label$2
(i32.lt_s
(get_local $0)
(get_local $2)
)
)
)
)
(set_local $1
(i32.add
(get_local $1)
(i32.const 1)
)
)
(br_if $label$0
(i32.ne
(tee_local $2
(i32.add
(get_local $2)
(i32.const 1)
)
)
(i32.const 100000)
)
)
)
(get_local $4)
)
)
Higher Language (C)
int main(void)
{
int numbers = 0;
for (int i=2; i<100000; i++)
{
for (int j=2; j<=i; j++)
{
if (i == j)
numbers++;
else if (i%j == 0)
break;
}
}
return numbers;
}