Vice Underdogs

Scripting => Script Showroom => Topic started by: stormeus on February 01, 2016, 09:47:31 am

Title: Performance benchmarks: Vector.Distance vs. Sqrt
Post by: stormeus on February 01, 2016, 09:47:31 am
I'm not sure if people ever noticed this with the 0.4 Squirrel releases, but vectors have some added functions for doing basic mathematical calculations on points/vectors, including:

I think prior to this, people mostly used the in-built sqrt() function in Squirrel to calculate the distances between points. I was curious to see if this would incur a performance penalty, since the vector functions exist in C++ in the Squirrel core, whereas sqrt() might be interpreted by Squirrel instead.

I did some basic benchmarking and as it turns out, Vector.Distance is more efficient than using sqrt(x^2 + y^2 + z^2). More interestingly, it seems that Vector.Distance can be as much as 10x faster.

(https://viceunderdogs.com/proxy.php?request=http%3A%2F%2Fi.imgur.com%2FaIVv60J.png&hash=e83422d402dc411f8fdbb577859e1ed87080a116)

Benchmark code
Code: [Select]
local start = 0;
local elapsed = 0;
local i;
local distance;

local point1 = Vector(867.5309, 2.201, 3.44);
local point2 = Vector(-3.75, -3.691, 3.1415926);

print("Point1: " + point1);
print("Point2: " + point2);

//-------------------------------------------//
start = GetTickCount();
for (i = 0; i < 1000000; i++) {
local dx = point2.x - point1.x;
local dy = point2.y - point1.y;
local dz = point2.z - point1.z;

distance = sqrt(dx * dx + dy * dy + dz * dz);
}

print("Sqrt distance: " + distance);
elapsed = GetTickCount() - start;

print("Sqrt loop: " + elapsed + "ms");
//-------------------------------------------//
start = GetTickCount();
for (i = 0; i < 1000000; i++) {
distance = point1.Distance(point2);
}

print("Call distance: " + distance);
elapsed = GetTickCount() - start;

print("Call loop: " + elapsed + "ms");
//-------------------------------------------//

This isn't to say that slow code is because you're using sqrt, or that everyone should immediately get to work on converting their code to use Vector.Distance, because this is micro-optimizing. The benchmarks were done over a million iterations (1,000,000) and so this would have no significant impact unless you were calculating vector distances very often. I just thought it was fun to note, since mathematical operations are typically pretty fast even in scripting languages.
Title: Re: Performance benchmarks: Vector.Distance vs. Sqrt
Post by: Drake on February 01, 2016, 12:41:31 pm
What about DistanceFromPoint? http://wiki.vc-mp.org/wiki/Scripting/Squirrel/Functions/DistanceFromPoint (http://wiki.vc-mp.org/wiki/Scripting/Squirrel/Functions/DistanceFromPoint)

And I never knew that those Vector things existed!
Title: Re: Performance benchmarks: Vector.Distance vs. Sqrt
Post by: EvilSpiriT on February 02, 2016, 06:01:41 am
Is this really helpful in calculating cross products too ?