Skip to content

Instantly share code, notes, and snippets.

@mlubin
Last active May 24, 2017 04:40
Show Gist options
  • Select an option

  • Save mlubin/4994c65c7a2fa90a3c7e to your computer and use it in GitHub Desktop.

Select an option

Save mlubin/4994c65c7a2fa90a3c7e to your computer and use it in GitHub Desktop.

Revisions

  1. mlubin revised this gist Jan 27, 2015. 1 changed file with 2 additions and 4 deletions.
    6 changes: 2 additions & 4 deletions newton_raw.c
    Original file line number Diff line number Diff line change
    @@ -27,11 +27,9 @@ int main()
    {
    const int num_iter = 100000;
    double t = clock_now();
    volatile double result_real;
    double sum_real = 0;
    volatile double sum_real = 0;
    for (int i = 0; i < num_iter; i++) {
    result_real = squareroot(10000.0);
    sum_real += result_real;
    sum_real += squareroot(10000.0);
    }
    double t_double = clock_now() - t;
    printf("%e seconds\n", t_double/num_iter);
  2. mlubin revised this gist Jan 27, 2015. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion newton.jl
    Original file line number Diff line number Diff line change
    @@ -8,7 +8,7 @@ end

    function time_sqrt(x)
    const num_iter = 100000
    q = one(x)
    q = zero(x)
    t = time()
    for i in 1:num_iter
    q += squareroot(x)
  3. mlubin created this gist Jan 27, 2015.
    21 changes: 21 additions & 0 deletions newton.jl
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    function squareroot(x)
    it = x
    while abs(it*it - x) > 1e-13
    it = it - (it*it-x)/(2it)
    end
    return it
    end

    function time_sqrt(x)
    const num_iter = 100000
    q = one(x)
    t = time()
    for i in 1:num_iter
    q += squareroot(x)
    end
    t = time() - t
    @show t/num_iter
    return q
    end

    time_sqrt(10000.0)
    38 changes: 38 additions & 0 deletions newton_raw.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    #include <stdio.h>
    #include <math.h>
    #include <sys/time.h>

    /*
    gcc -O2 --std=c99 -march=native -o newton_raw newton_raw.c
    clang -O2 --std=c99 -o newton_raw newton_raw.c
    */

    // copied from julia
    double clock_now()
    {
    struct timeval now;
    gettimeofday(&now, NULL);
    return (double)now.tv_sec + (double)now.tv_usec/1.0e6;
    }

    double squareroot(double x)
    {
    double it = x;
    while (fabs(it*it - x) > 1e-13) {
    it = it - (it*it-x)/(2*it);
    }
    return it;
    }
    int main()
    {
    const int num_iter = 100000;
    double t = clock_now();
    volatile double result_real;
    double sum_real = 0;
    for (int i = 0; i < num_iter; i++) {
    result_real = squareroot(10000.0);
    sum_real += result_real;
    }
    double t_double = clock_now() - t;
    printf("%e seconds\n", t_double/num_iter);
    }