Skip to content

Instantly share code, notes, and snippets.

@mlubin
Last active May 24, 2017 04:40
Show Gist options
  • Save mlubin/4994c65c7a2fa90a3c7e to your computer and use it in GitHub Desktop.
Save mlubin/4994c65c7a2fa90a3c7e to your computer and use it in GitHub Desktop.
julia/C microbenchmark
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 = zero(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)
#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 sum_real = 0;
for (int i = 0; i < num_iter; i++) {
sum_real += squareroot(10000.0);
}
double t_double = clock_now() - t;
printf("%e seconds\n", t_double/num_iter);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment