c:compute-execution-time
Differences
This shows you the differences between two versions of the page.
Last revisionBoth sides next revision | |||
c:compute-execution-time [2024/01/17 01:12] – created odefta | c:compute-execution-time [2024/01/17 01:15] – odefta | ||
---|---|---|---|
Line 26: | Line 26: | ||
</ | </ | ||
+ | Concrete example - Bubble Sort: | ||
+ | |||
+ | <code c bubble-sort-exec-time.c> | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | |||
+ | #define ARRAY_SIZE 10000 | ||
+ | |||
+ | // Functie pentru bubble sort | ||
+ | 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; | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | |||
+ | // Functie pentru a umple array-ul cu valori aleatoare | ||
+ | void fillArray(int arr[], int n) { | ||
+ | for (int i = 0; i < n; i++) { | ||
+ | arr[i] = rand() % 1000; // Numere aleatoare între 0 și 999 | ||
+ | } | ||
+ | } | ||
+ | |||
+ | // Functie pentru afisarea array-ului | ||
+ | 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(& | ||
+ | |||
+ | // Executarea algoritmului de sortare | ||
+ | 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.txt · Last modified: 2024/01/17 01:16 by odefta