1

I'm comparing the performance of boost's gmp_rational datatype with the SolverFoundation.Rational type of C#. Performing arithmetic with gmp_rational is much faster than C# SolverFoundation.Rational, except for comparison operations. I have implemented the following function in C++ and C# and made a comparison of its performance.

typedef mpq_rational NT;
void test()
{
    NT x = 3.05325557;
    NT y = 2.65684334;
    NT z, j, k;

    std::clock_t start;
    double duration;

    start = std::clock();

    for(int i = 0; i < 10000; i++)
    {
        if (i%1000 == 0)
            x = 3;
        x = x * y;
        z = x + y;
        j = x + y;
        k = x + y;
        bool r1 = j > k; // takes very long
    }

    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
    std::cout<<"duration: "<< duration <<'\n';    
}

Without the last comparison operation "j > k", the function needs 5.5 seconds. With it, the function needs 33 seconds.

I have implemented the same method in C# and did the same comparison. Without the last comparison operation "j > k", the method needs 19 seconds. With it, the method needs 19.6 seconds. So the C# code is even faster than the C++ code, but I don't understand why.

NMO
  • 748
  • 8
  • 16
  • bool r1 = j > k; can be completely eliminated by the compiler, so what does it prove? You could try and inspect generated assembler (or disasemble generated code) – aka.nice May 21 '16 at 18:23
  • To make it more convincing, you should make r1 volatile, and compare with the time it takes if you replace `j>k` with `(j-k)>0`. And indeed I see a factor 5 in performance between the 2 versions, that's weird. You may want to report it https://gmplib.org/manual/Reporting-Bugs.html . – Marc Glisse May 21 '16 at 22:08
  • 1
    Ah, it may be that for subtraction, GMP simplifies by the gcd while for comparison, it multiplies directly. In this particular case (the 2 numbers are equal), the benefit of looking at the gcd is maximized. If I increment the denominator by 1 in one of the numbers before the comparison, cmp is now twice as fast as the subtraction version. – Marc Glisse May 21 '16 at 22:36

0 Answers0