User Tools

Site Tools


c:compute-execution-time

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
c:compute-execution-time [2024/01/17 01:12] – created odeftac:compute-execution-time [2024/01/17 01:16] (current) odefta
Line 26: Line 26:
 </code> </code>
  
 +Concrete example - Bubble Sort:
 +
 +<code c bubble-sort-exec-time.c>
 +#include <stdio.h>
 +#include <stdlib.h>
 +#include <sys/time.h>
 +
 +#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("%d ", arr[i]);
 +    }
 +    printf("\n");
 +}
 +
 +int main() {
 +    int arr[ARRAY_SIZE];
 +    struct timeval start, end;
 +
 +    fillArray(arr, ARRAY_SIZE);
 +
 +    // Start the timer
 +    gettimeofday(&start, NULL);
 +
 +    // Execute the sorting algorithm
 +    bubbleSort(arr, ARRAY_SIZE);
 +
 +    // End the timer
 +    gettimeofday(&end, NULL);
 +
 +    // 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("Time elapsed: %ld microseconds (%.6f seconds)\n", micros, time_in_seconds);
 +
 +    // Optional: Print sorted array
 +    // printArray(arr, ARRAY_SIZE);
 +
 +    return 0;
 +}
 +</code>
c/compute-execution-time.1705446766.txt.gz · Last modified: 2024/01/17 01:12 by odefta