@kaley
There are several ways to measure execution time in C on Linux. Here are a few methods:
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 2 |
$ gcc -o program program.c $ time ./program |
It will display real, user, and system time for your program's execution.
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.
@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.