-
-
Save ajfriend/32571f0af1f3ea3133b6836fc861c730 to your computer and use it in GitHub Desktop.
Timing for shift vs mask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
all: thing run | |
thing: | |
gcc -Wall -Wextra -std=c99 -O3 test.c -o test | |
run: | |
./test |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdint.h> | |
#include <stdlib.h> | |
#include <inttypes.h> | |
#include <time.h> | |
// void qsort(void* base, size_t num, size_t size, int (*comparator)(const void*,const void*)); | |
// printf("\nSorted:\n"); | |
// for(int i = 0; i < N; i++){ | |
// printf("%" PRIu64 "\n", a[i]); | |
// } | |
// printf("Unsorted:\n"); | |
// for(int i = 0; i < N; i++){ | |
// printf("%" PRIu64 "\n", a[i]); | |
// } | |
// printf("%" PRIu64 "\n", t >> 60); | |
#define IMAX_BITS(m) ((m)/((m)%255+1) / 255%255*8 + 7-86/((m)%255+12)) | |
#define RAND_MAX_WIDTH IMAX_BITS(RAND_MAX) | |
_Static_assert((RAND_MAX & (RAND_MAX + 1u)) == 0, "RAND_MAX not a Mersenne number"); | |
uint64_t rand64(void) { | |
uint64_t r = 0; | |
for (int i = 0; i < 64; i += RAND_MAX_WIDTH) { | |
r <<= RAND_MAX_WIDTH; | |
r ^= (unsigned) rand(); | |
} | |
return r; | |
} | |
#define MAKE_CMP_FUNC(name, expression) \ | |
int (name)(const void *p, const void *q){ \ | |
uint64_t l = *(const uint64_t *)p; \ | |
uint64_t r = *(const uint64_t *)q; \ | |
expression \ | |
if (l < r) return -1; \ | |
if (l > r) return +1; \ | |
return 0; \ | |
} \ | |
MAKE_CMP_FUNC(cmp_std, | |
) | |
MAKE_CMP_FUNC(cmp_shift, | |
l <<= 12; | |
r <<= 12; | |
) | |
MAKE_CMP_FUNC(cmp_mask, | |
uint64_t m = 0x000fffffffffffff; | |
l &= m; | |
r &= m; | |
) | |
// todo: maybe make this a function | |
#define DO_TIMING(cmp_func) \ | |
copy(a, b, N); \ | |
start_time = clock(); \ | |
qsort((void*)b, N, sizeof(b[0]), (cmp_func)); \ | |
end_time = clock(); \ | |
time_elapsed = (end_time - start_time)/CLOCKS_PER_SEC; \ | |
printf(#cmp_func ": %f\n", time_elapsed); \ | |
void copy(uint64_t * x, uint64_t * y, uint64_t N){ | |
for(uint64_t i = 0; i < N; i++){ | |
y[i] = x[i]; | |
} | |
} | |
int main() { | |
uint64_t N = 3000000; | |
uint64_t a[N]; | |
uint64_t b[N]; | |
double start_time, end_time, time_elapsed; | |
srand(3); | |
for(uint64_t i = 0; i < N; i++){ | |
a[i] = rand64(); | |
} | |
for(uint64_t i = 0; i < 10; i++){ | |
DO_TIMING(cmp_std); | |
DO_TIMING(cmp_shift); | |
DO_TIMING(cmp_mask); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment