Skip to content

Instantly share code, notes, and snippets.

@mpgn
Last active August 29, 2015 14:07
Show Gist options
  • Save mpgn/0f3fcf736e13ef5e484a to your computer and use it in GitHub Desktop.
Save mpgn/0f3fcf736e13ef5e484a to your computer and use it in GitHub Desktop.
C pow vs shift
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <time.h>
int main() {
const size_t nTests = 10000000;
const size_t nExp = 10000;
int e[nExp];
/* Make an array of random exponents to use in tests. */
srand( (unsigned int)time(NULL) );
for( int i = 0; i < nExp; i++ ) e[i] = rand() % 31;
int sumPow = 0;
int sumShift = 0;
clock_t startPOW = clock(), diffPOW;
for(int i = 0; i < nTests; i++) {
int y = (int)pow(2,(double)e[i%nExp]);
sumPow += y;
}
diffPOW = clock() - startPOW;
clock_t startS = clock(), diffS;
for(int i = 0; i < nTests; i++) {
int y = 1ULL << e[i%nExp];
sumShift += y;
}
diffS = clock() - startS;
int msecPOW = diffPOW * 1000 / CLOCKS_PER_SEC;
int msecS = diffS * 1000 / CLOCKS_PER_SEC;
printf("Tests pow VS shift\n");
printf("10 000 000 perform...\n");
printf("...\n");
printf("Sum pow:%d\n", sumPow);
printf("Sum shift:%d\n", sumShift);
printf("Time taken by pow %d milliseconds\n", msecPOW%1000);
printf("Time taken by shift %d milliseconds\n", msecS%1000);
printf("Time ratio of pow versus shift: %ju\n", diffPOW/diffS);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment