Created
January 6, 2021 11:47
-
-
Save hjiang/a8a154995e1bb57694bece4eeb402d5c to your computer and use it in GitHub Desktop.
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 <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