Created
December 16, 2016 15:21
-
-
Save ftonello/c104a8e407528e1ff9c3dfc8711834aa to your computer and use it in GitHub Desktop.
swap test
This file contains hidden or 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 <stddef.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <sys/time.h> | |
#include <time.h> | |
static long long int ts_us() | |
{ | |
struct timeval tv; | |
struct timezone tz; | |
gettimeofday(&tv, &tz); | |
return ((long long int)tv.tv_sec * 1000000) + tv.tv_usec; | |
} | |
static inline void memswap1(uint8_t *a, uint8_t *b, size_t size) | |
{ | |
while(size--) { | |
*a ^= *b; | |
*b ^= *a; | |
*a ^= *b; | |
a++; | |
b++; | |
} | |
} | |
static inline void memswap2(uint8_t *a, uint8_t *b, size_t size) | |
{ | |
uint8_t v; | |
while(size--) { | |
v = *b; | |
*b = *a; | |
*a = v; | |
a++; | |
b++; | |
} | |
} | |
int main () | |
{ | |
struct { | |
int a, b, c; char d, e; int f; | |
} A = {12414, 42542, 253252, 123, 43, 134151}, | |
B = {145151, 422, 123141, 12, 45, 13141511}; | |
/* int A = 10, B = 20; */ | |
long long int n, b4, af; | |
n = 1000000000; | |
b4 = ts_us(); | |
while(n--) | |
memswap1((uint8_t *)&A, (uint8_t *)&B, sizeof(A)); | |
af = ts_us(); | |
printf("Swap1\nElapsed %lld us\nPer swap: %f ns\n\n", | |
af - b4, (double)(af-b4)/1000000.0); | |
n = 1000000000; | |
b4 = ts_us(); | |
while(n--) | |
memswap2((uint8_t *)&A, (uint8_t *)&B, sizeof(A)); | |
af = ts_us(); | |
printf("Swap2\nElapsed %lld us\nPer swap: %f ns\n\n", | |
af - b4, (double)(af-b4)/1000000.0); | |
n = 1000000000; | |
b4 = ts_us(); | |
typeof(A) tmp; | |
while(n--) { | |
tmp = A; | |
A = B; | |
B = tmp; | |
} | |
af = ts_us(); | |
printf("Swap3\nElapsed %lld us\nPer swap: %f ns\n\n", | |
af - b4, (double)(af-b4)/1000000.0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment