var i;
var r;
var v = 2**16;
function test1() {
for(i=0; i < 1000; ++i) {
r = 1 / Math.sqrt(v);
}
}
function test2() {
for(i=0; i < 1000; ++i) {
r = Q_rsqrt(v);
}
}
//Based on the fast inverse square root function
// https://en.wikipedia.org/wiki/Fast_inverse_square_root
// Some original comments preserved for humor value
// Designed to try to mimic the original as closely as possible
function Q_rsqrt(number)
{
var i;
var x2, y;
const threehalfs = 1.5;
x2 = number * 0.5;
y = number;
//evil floating bit level hacking
var buf = new ArrayBuffer(4);
(new Float32Array(buf))[0] = number;
i = (new Uint32Array(buf))[0];
i = (0x5f3759df - (i >> 1)); //What the fuck?
(new Uint32Array(buf))[0] = i;
y = (new Float32Array(buf))[0];
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
test1();
test2();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Math.sqrt | |
Quakes fast inverse sqrt. |
Test name | Executions per second |
---|---|
Math.sqrt | 6873.2 Ops/sec |
Quakes fast inverse sqrt. | 1472.3 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The provided JSON represents a benchmark definition for a JavaScript function called Fast Sqrt 2234234
. This function is designed to compare two implementations of fast inverse square root calculations, specifically:
Math.sqrt
method.Q_rsqrt
).The benchmark measures the performance difference between these two approaches.
Options Compared
The main options being compared are:
Pros and Cons
Here's a brief analysis of each approach:
Library: Quakes
The Q_rsqrt
function is implemented in JavaScript, but it relies on some mathematical tricks and bit-level manipulation. The library used for this implementation is not explicitly stated, but it's likely a custom-built library optimized for performance.
Special JS Feature/Syntax
This benchmark uses some special JavaScript features, such as:
0x5f3759df - (i >> 1)
).(new Float32Array(buf))[0] = number;
).These features are specific to the implementation and may not be widely supported or understood.
Other Alternatives
If you're interested in exploring other approaches, here are a few alternatives:
Keep in mind that implementing these alternatives will require a good understanding of low-level computer science and programming expertise.
I hope this explanation helps you understand the basics of the JavaScript microbenchmark on MeasureThat.net!