User Tools

Site Tools


c:compute-execution-time

Compute execution time of a C program

Normal usage:

execution-time.c
#include <sys/time.h>
#include <stdio.h>
 
struct timeval start, end;
 
// Start the timer
gettimeofday(&start, NULL);
 
// Here is the code to be executed
 
// 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);

Concrete example - Bubble Sort:

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;
}
c/compute-execution-time.txt · Last modified: 2024/01/17 01:16 by odefta