I compiled the same approximate version to C with gcc optimisations on, and 
found the execution time to be roughly comparable between Nim and C. Could 
Julia's JIT be doing some sort of optimisation that shortcuts the full code 
somehow?

With the Nim version:
    
    
    import times, math
    
    proc leibniz(terms: int): float =
        var res = 0.0
        for n in 0..terms:
            res += pow(-1.0,float(n))/(2.0*float(n)+1.0)
        return 4*res
    
    let t0 = cpuTime()
    echo(leibniz(100_000_000))
    let t1 = cpuTime()
    echo "Elapsed time: ", $(t1 - t0)
    
    

I got these output times:

C:projectsNim>nim_version 3.141592663589326 Elapsed time: 6.541

C:projectsNim>nim_version 3.141592663589326 Elapsed time: 6.676

C:projectsNim>nim_version 3.141592663589326 Elapsed time: 6.594

While with the same C version:
    
    
    #include <stdio.h>
    #include <math.h>
    #include <time.h>
    
    double leibniz(int terms) {
            double res = 0.0;
        for (int i = 0; i < terms; ++i) {
            res += pow(-1.0, (double)i) / (2.0 * (double)i + 1.0);
        }
        return 4*res;
    }
    
    int main() {
        clock_t start = clock();
        double x = leibniz(100000000);
        printf("%.15f\n", x);
        printf("Time elapsed: %f\n", ((double)clock() - start) / 
CLOCKS_PER_SEC);
    }
    
    

The times taken were (EDIT: used -Ofast instead and got faster times):

C:projectsc>c_version 3.141592643589326 Time elapsed: 6.206000

C:projectsc>c_version 3.141592643589326 Time elapsed: 6.204000

C:projectsc>c_version 3.141592643589326 Time elapsed: 6.217000

I realise I actually got a slightly different decimal number with C, but to be 
honest I am not a C programmer so I am sure I did something wrong in the 
formatting.

Reply via email to