c:compute-execution-time
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
c:compute-execution-time [2024/01/17 01:12] – created odefta | c:compute-execution-time [2024/01/17 01:16] (current) – odefta | ||
---|---|---|---|
Line 26: | Line 26: | ||
</ | </ | ||
+ | Concrete example - Bubble Sort: | ||
+ | |||
+ | <code c bubble-sort-exec-time.c> | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | |||
+ | #define ARRAY_SIZE 10000 | ||
+ | |||
+ | void bubbleSort(int arr[], int n) { | ||
+ | int i, j, temp; | ||
+ | for (i = 0; i < n - 1; i++) { | ||
+ | for (j = 0; j < n - i - 1; j++) { | ||
+ | if (arr[j] > arr[j + 1]) { | ||
+ | temp = arr[j]; | ||
+ | arr[j] = arr[j + 1]; | ||
+ | arr[j + 1] = temp; | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | |||
+ | void fillArray(int arr[], int n) { | ||
+ | for (int i = 0; i < n; i++) { | ||
+ | arr[i] = rand() % 1000; // Random numbers between 0 and 999 | ||
+ | } | ||
+ | } | ||
+ | |||
+ | void printArray(int arr[], int n) { | ||
+ | for (int i = 0; i < n; i++) { | ||
+ | printf(" | ||
+ | } | ||
+ | printf(" | ||
+ | } | ||
+ | |||
+ | int main() { | ||
+ | int arr[ARRAY_SIZE]; | ||
+ | struct timeval start, end; | ||
+ | |||
+ | fillArray(arr, | ||
+ | |||
+ | // Start the timer | ||
+ | gettimeofday(& | ||
+ | |||
+ | // Execute the sorting algorithm | ||
+ | bubbleSort(arr, | ||
+ | |||
+ | // End the timer | ||
+ | gettimeofday(& | ||
+ | |||
+ | // Calculating the time difference in seconds and microseconds | ||
+ | long seconds = end.tv_sec - start.tv_sec; | ||
+ | long micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec); | ||
+ | |||
+ | // Convert time to seconds and print | ||
+ | double time_in_seconds = seconds + micros / 1000000.0; | ||
+ | printf(" | ||
+ | |||
+ | // Optional: Print sorted array | ||
+ | // printArray(arr, | ||
+ | |||
+ | return 0; | ||
+ | } | ||
+ | </ |
c/compute-execution-time.1705446766.txt.gz · Last modified: 2024/01/17 01:12 by odefta