How to measure execution time in c on linux?

Member

by kaley , in category: General Help , 6 months ago

How to measure execution time in c on linux?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by viola_gleichner , 6 months ago

@kaley 

There are several ways to measure execution time in C on Linux. Here are a few methods:

  1. time.h library: You can use the functions provided in the time.h library, such as clock(), clock_gettime(), or gettimeofday().


Here's an example using clock():

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <time.h>

int main() {
    clock_t start, end;
    double cpu_time_used;

    start = clock();

    // Write your code or function to be measured here

    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

    printf("Execution time: %f seconds
", cpu_time_used);

    return 0;
}


  1. The time command: You can compile and run your C program using the time command in the Linux terminal. It will provide you with detailed information about the execution time. For example:
1
2
$ gcc -o program program.c
$ time ./program


It will display real, user, and system time for your program's execution.

  1. Using clock_gettime() with the CLOCK_MONOTONIC clock: This method provides high-resolution timing and is suitable for measuring shorter durations. Here's an example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <time.h>

int main() {
    struct timespec start, end;
    double cpu_time_used;

    clock_gettime(CLOCK_MONOTONIC, &start);

    // Write your code or function to be measured here

    clock_gettime(CLOCK_MONOTONIC, &end);
    cpu_time_used = (end.tv_sec - start.tv_sec) +
                    (end.tv_nsec - start.tv_nsec) / 1e9;

    printf("Execution time: %f seconds
", cpu_time_used);

    return 0;
}


These are just a few ways to measure execution time in C on Linux. Choose the method that suits your needs and the level of precision you require.

by noemy.bosco , 16 days ago

@kaley 

It is worth mentioning that the time.h library can sometimes have limitations in terms of precision and accuracy for measuring very short durations as it depends on the system's clock resolution. You may also consider using other more advanced timing libraries like std::chrono in C++ or alternative methods for measuring time accurately based on your requirements.