fork(43) download
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <time.h>
  4.  
  5. #define MAX_COUNT (1 << 29)
  6. size_t counter = 0;
  7.  
  8. size_t testSwitch()
  9. {
  10. clock_t start = clock();
  11. size_t i;
  12. for (i = 0; i < MAX_COUNT; i++)
  13. {
  14. switch (counter % 4 + 1)
  15. {
  16. case 1: counter += 4; break;
  17. case 2: counter += 3; break;
  18. case 3: counter += 2; break;
  19. case 4: counter += 1; break;
  20. }
  21. }
  22. return 1000 * (clock() - start) / CLOCKS_PER_SEC;
  23. }
  24.  
  25. size_t testIf()
  26. {
  27. clock_t start = clock();
  28. size_t i;
  29. for (i = 0; i < MAX_COUNT; i++)
  30. {
  31. const size_t c = counter % 4 + 1;
  32. if (c == 1) { counter += 4; }
  33. else if (c == 2) { counter += 3; }
  34. else if (c == 3) { counter += 2; }
  35. else if (c == 4) { counter += 1; }
  36. }
  37. return 1000 * (clock() - start) / CLOCKS_PER_SEC;
  38. }
  39.  
  40. int main()
  41. {
  42. printf("Starting...\n");
  43. printf("Switch statement: %u ms\n", testSwitch());
  44. printf("If statement: %u ms\n", testIf());
  45. }
Success #stdin #stdout 1.32s 4568KB
stdin
Standard input is empty
stdout
Starting...
Switch statement: 1034 ms
If     statement: 278 ms