Skip to content

Instantly share code, notes, and snippets.

@dim13
Last active July 22, 2016 19:07
Show Gist options
  • Save dim13/a74ac5b1ae203325c78860fac079ec80 to your computer and use it in GitHub Desktop.
Save dim13/a74ac5b1ae203325c78860fac079ec80 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <time.h>
int
dummy(int n)
{
return -1;
}
#define nelem(x) (sizeof(x) / sizeof((x)[0]))
#define value(x) ((x) + 1)
int map[] = {
[1] = value(77),
[7] = value(2),
[9] = value(11),
[11] = value(8),
[31] = value(81),
[77] = value(5),
[81] = value(333),
[9999] = value(0),
};
int
getmap(int a)
{
if (a >= 0 && a < nelem(map))
return map[a] - 1;
return -1;
}
int
getswitch(int a)
{
switch (a) {
case 1: return 77;
case 7: return 2;
case 9: return 11;
case 11: return 8;
case 31: return 81;
case 77: return 5;
case 81: return 333;
case 9999: return 0;
default: return -1;
}
}
#define QSIZE 3
int tr[] = {
31, 16, 81, 10, 9999, 8, 9999, 0,
81, 333, 77, 14, 77, 5, 31, 81,
9, 24, 11, 22, 11, 8, 9, 99,
7, 28, 7, 2, 1, 77};
int
translate(int input)
{
int idx = 0;
int i;
for (i = 0; i < QSIZE; ++i) {
if (input < tr[idx]) {
idx = tr[idx + 1];
} else {
idx += 2;
}
}
if (input == tr[idx]) {
return tr[idx+1];
}
return -1;
}
int
f(int x) {
if (x<=3) {
switch (x) {
case 0: return 10;
case 1: return 11;
case 2: return 12;
case 3: return 13;
default: return -1;
}
} else {
if (x<=7) {
switch (x) {
case 4: return 14;
case 7: return 17;
default: return -1;
}
} else {
switch (x) {
case 105: return 3453;
case 777: return 5;
case 999: return 666;
default: return -1;
}
}
}
}
void
bench(int (*f)(int), char *name, int n) {
int i, j;
float start = (float)clock()/CLOCKS_PER_SEC;
for (i = 0; i < n; i++)
for (j = 0; j < 1000; j++)
f(j);
float end = (float)clock()/CLOCKS_PER_SEC;
printf("%d times %s: %fs\n", n, name, end-start);
}
int
main()
{
int n = 1000000;
bench(dummy, "dummy", n);
bench(getmap, "map", n);
bench(getswitch, "switch", n);
bench(translate, "translate", n);
bench(f, "f", n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment