Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <time.h>
#include <stdio.h>
int main() {
int i;
int j;
int k;
int a;
int b;
const int n = 100000000;
clock_t start;
clock_t end;
printf("============= warm up ==============\n");
i = 0;
a = 0;
start = clock();
while (i < n) {
if (i % 3 == 0) {
a += i*2;
} else {
a -= i;
}
i++;
}
end = clock();
printf("a: %d\n", a); // make sure a is not optimized away
printf("t1: %ld\n", end - start);
j = 0;
b = 0;
start = clock();
while (j < n) {
if (j % 7 == 0) {
b += j*6;
} else {
b -= j;
}
j++;
}
end = clock();
printf("b: %d\n", b);
printf("t2: %ld\n", end - start);
i = 0;
j = 0;
a = 0;
b = 0;
k = 0;
start = clock();
while (k < n) {
if (i % 3 == 0) {
a += i*2;
} else {
a -= i;
}
i++;
if (j % 7 == 0) {
b += j*6;
} else {
b -= j;
}
j++;
k++;
}
end = clock();
printf("a: %d\n", a);
printf("b: %d\n", b);
printf("t3: %ld\n", end - start);
printf("============= benchmark ==============\n");
i = 0;
a = 0;
start = clock();
while (i < n) {
if (i % 3 == 0) {
a += i*2;
} else {
a -= i;
}
i++;
}
end = clock();
printf("a: %d\n", a); // make sure a is not optimized away
printf("t1: %ld\n", end - start);
j = 0;
b = 0;
start = clock();
while (j < n) {
if (j % 7 == 0) {
b += j*6;
} else {
b -= j;
}
j++;
}
end = clock();
printf("b: %d\n", b);
printf("t2: %ld\n", end - start);
i = 0;
j = 0;
a = 0;
b = 0;
k = 0;
start = clock();
while (k < n) {
if (i % 3 == 0) {
a += i*2;
} else {
a -= i;
}
i++;
if (j % 7 == 0) {
b += j*6;
} else {
b -= j;
}
j++;
k++;
}
end = clock();
printf("a: %d\n", a);
printf("b: %d\n", b);
printf("t3: %ld\n", end - start);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment