darraghd493

Basic While vs For vs Do Function Timer

Jul 28th, 2022
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.47 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <time.h>
  3.  
  4. void while_loop(int target) {
  5.     int i = 0;
  6.     while (i < target) {
  7.         printf("%d\n", i);
  8.         i++;
  9.     }
  10. }
  11.  
  12. void for_loop(int target) {
  13.     for (int i = 0; i < target; i++) {
  14.         printf("%d\n", i);
  15.     }
  16. }
  17.  
  18. void do_loop(int target) {
  19.     int i = 0;
  20.     do {
  21.         printf("%d\n", i);
  22.         i++;
  23.     } while (i < target);
  24. }
  25.  
  26. int main() {
  27.     int target = 0;
  28.     printf("Enter the target amount: ");
  29.     scanf("%d", &target);
  30.  
  31.     printf("What function do you want to measure?\n\n");
  32.     printf("1. While loop\n");
  33.     printf("2. For loop\n");
  34.     printf("3. Do loop\n");
  35.     printf("4. Exit\n\n");
  36.    
  37.     int choice = 0;
  38.     printf("Enter your choice: ");
  39.     scanf("%d", &choice);
  40.  
  41.     clock_t start = NULL;
  42.     switch (choice) {
  43.         case 1:
  44.             start = clock();
  45.             while_loop(target);
  46.             break;
  47.         case 2:
  48.             start = clock();
  49.             for_loop(target);
  50.             break;
  51.         case 3:
  52.             start = clock();
  53.             do_loop(target);
  54.             break;
  55.         case 4:
  56.             break;
  57.         default:
  58.             printf("Invalid choice\n");
  59.             break;
  60.     }
  61.  
  62.     if (start != NULL) {
  63.         clock_t end = clock();
  64.         double time_spent = (double)(end - start) / CLOCKS_PER_SEC;
  65.         printf("Time spent: %f\n", time_spent);
  66.     } else {
  67.         printf("No time spent\n");
  68.     }
  69.  
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment