Skip to content

Instantly share code, notes, and snippets.

@lubo
Last active October 28, 2015 11:53
Show Gist options
  • Save lubo/667b5e02ba3d87a60e1e to your computer and use it in GitHub Desktop.
Save lubo/667b5e02ba3d87a60e1e to your computer and use it in GitHub Desktop.
An example program demonstrating time efficiency of different number-swapping algorithms
#include <stdio.h>
#include <time.h>
#include <inttypes.h>
typedef struct {
void (*function) (uint32_t *a, uint32_t *b);
char *description;
} swapping_method;
void swap_temp(uint32_t *a, uint32_t *b) {
uint32_t c = *a;
*a = *b;
*b = c;
}
void swap_pointers(uint32_t *a, uint32_t *b) {
uint32_t *c = a;
a = b;
b = c;
}
void swap_sum(uint32_t *a, uint32_t *b) {
*a += *b;
*b = *a - *b;
*a -= *b;
}
void swap_xor(uint32_t *a, uint32_t *b) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
swapping_method methods[] = {
{
.function = swap_temp,
.description = "temporary integer"
},
{
.function = swap_pointers,
.description = "temporary pointer"
},
{
.function = swap_sum,
.description = "sum and difference"
},
{
.function = swap_xor,
.description = "XOR"
}
};
int main() {
for (int i = 0; i < sizeof(methods) / sizeof (swapping_method); i++) {
uint32_t a = 0, b = 1;
swapping_method method = methods[i];
clock_t start = clock();
for (int n = 0; n < 600000000; n++) {
method.function(&a, &b);
}
clock_t end = clock();
printf("Swapping integers using %s takes %f s\n", method.description,
(float) (end - start) / CLOCKS_PER_SEC);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment