Skip to content

Instantly share code, notes, and snippets.

@avshabanov
Created June 2, 2014 17:39
Show Gist options
  • Save avshabanov/b4960e95c8b68575ad27 to your computer and use it in GitHub Desktop.
Save avshabanov/b4960e95c8b68575ad27 to your computer and use it in GitHub Desktop.
Performance benchmark: double multiplication vs integer multiplication+shift
#include <stdio.h>
#define N (100000000)
double arr[] = { 8, 0.125, 4, 0.25 };
int main() {
double d = 1.0;
for (int i = 0; i < N; ++i) {
d *= arr[i % 4];
}
fprintf(stderr, "d = %f\n", d);
return 0;
}
#include <stdio.h>
#define N (100000000)
struct muls_t {
long long mul;
int shr; // shift right (division)
};
struct muls_t arr[] = { {8, 0}, {1, 3}, {4, 0}, {1, 2} };
int main() {
long long d = 1;
for (int i = 0; i < N; ++i) {
struct muls_t m = arr[i % 4];
d = (d * m.mul) >> m.shr;
}
fprintf(stderr, "d = %lld\n", d);
return 0;
}
# gcc perf_double.c -O3 -o pd
# gcc perf_int.c -O3 -o pi
# Mac Book Pro, late 2013
$ time ./pd
d = 1.000000
real 0m0.177s
user 0m0.166s
sys 0m0.002s
$ time ./pd
d = 1
real 0m0.184s
user 0m0.172s
sys 0m0.002s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment