Optimize this compass directions code

@Paul_McGee
I found some interesting things when playing with this (C++) code.
I compiled it using Qt Creator on Linux Mint but just as a standard C++ program with no Qt code.
I took your code and added another routine to test my straight double comparaison against the other methods. I then just ran the tests in order and found I was getting varying results but with consistent placings: CompassDirectionOf3 was consistently the fastest, the CompassDirnBybinary was consistently the slowest. They were all run from the IDE compiled with debug code.
Next I compiled a release version and the speed increase was remarkable and there was hardly any difference between the different routines.
The ultimate test was running a stand-alone executable and all methods returned a time of 100 nanoseconds or less for the 10 x 10,000,000 operations. The speed did vary between 60ns and 120ns but I guess that depended on CPU load at that exact point in time.
This was done on a Xeon 8 core with 32GB ram with GCC 9 but no optimisation or threading was done by me.
The main thing I found was how little the methods differed in their execution time.
I will try on Windows using Rad Studio and also Delphi when I get the time but it has been a very interesting exercise.

1 Like

Thanks for posting your results. I ran everything as Release build in the IDE.
It occurred to me after a few posts that I’m running on a Win10 laptop with 4 cores, and things will be different on other systems. Also C++Builder is Clang 5.0.0, which is a bit old now.
It hadn’t occurred to me to try it out on the gcc 9.2 that comes with Dev-cpp. :thinking:

And messing with it a bit earlier today, I wasn’t seeing a difference (in c++) between the cast to enum vs array lookup.
Both were coming up as 40 ms. Buggered if I know what I changed :sweat_smile: (although I guess Git can tell me).

@Paul_McGee
It will be interesting to hear your findings if you compile in Dev-cpp.
I have found (in general) that a program compiled with the same version of Qt will compile and run considerably faster on Linux than on Windows 10 (same computer).
As far as the original question, it doesn’t seem to matter which routine he uses - at least in C++. I will be interested to see it in Delphi. My Delphi installation is running in a Windows 10 VirtualBox with 4 cores allocated so it will be much slower but it is the comparison we’re interested in here :slight_smile:

1 Like

I was curious about trying various ways to approach this problem, focusing on the implementations.

But it occurs to me that this is a really good case for writing a bunch of tests first, and then writing the functions - and I feel like I need to go back and do it over that way. :thinking:

2 Likes