Skip to content

Instantly share code, notes, and snippets.

@davidjmemmett
Last active April 27, 2018 08:32
Show Gist options
  • Save davidjmemmett/8dad9b208a03a1863c6ce8f1c07f4b63 to your computer and use it in GitHub Desktop.
Save davidjmemmett/8dad9b208a03a1863c6ce8f1c07f4b63 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <sys/time.h>
int repetitions = 100000000;
double time_diff(struct timeval x, struct timeval y);
double native_add(double a, double b) {
double x;
int i;
for (i = 1; i <= repetitions; i++) {
x = a + b;
}
return x;
}
void native() {
struct timeval before, after;
gettimeofday(&before, NULL);
double x;
x = native_add(1.11, 1.19);
gettimeofday(&after, NULL);
printf("native answer: %f\n", x);
printf("Total time elapsed: %.0lf us\n", time_diff(before, after));
};
double twoints_add(double a, double b) {
int xa, xb, aa, ab, ba, bb;
int precision = 1000;
aa = (int)a;
ab = (int)(a * precision)-(aa * precision);
ba = (int)b;
bb = (int)(b * precision)-(ba * precision);
int i;
for (i = 1; i <= repetitions; i++) {
xa = aa + ba;
xb = ab + bb;
}
double result;
result = (double)xa;
result = result + ((double)xb / precision);
return result;
}
void twoints() {
struct timeval before, after;
gettimeofday(&before, NULL);
double x;
x = twoints_add(1.11, 1.19);
gettimeofday(&after, NULL);
printf("twoints answer: %f\n", x);
printf("Total time elapsed: %.0lf us\n", time_diff(before, after));
};
int main() {
native();
twoints();
return 0;
}
double time_diff(struct timeval x, struct timeval y) {
double x_ms, y_ms, diff;
x_ms = (double)x.tv_sec * 1000000 + (double)x.tv_usec;
y_ms = (double)y.tv_sec * 1000000 + (double)y.tv_usec;
diff = (double)y_ms - (double)x_ms;
return diff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment