Measure Execution Time in C: time(), clock() and gettimeofday()
This guide demonstrates how to use the C standard library functions time(), clock(), and the POSIX gettimeofday() to measure code execution duration, comparing their precision levels and showing sample code snippets that illustrate typical usage and output.
Measuring Seconds with time()
#include <stdio.h>
#include <time.h>
int main() {
// Get current time before operation
time_t start_time = time(NULL);
// Perform some operation (e.g., a simple loop)
for (long i = 0; i < 1000000000; ++i);
// Get current time after operation
time_t end_time = time(NULL);
// Compute time difference
double duration = difftime(end_time, start_time);
// Print time difference
printf("Elapsed time: %.2f seconds
", duration);
return 0;
}Sample output:
Elapsed time: 3.00 secondsMeasuring Higher Precision with clock()
#include <stdio.h>
#include <time.h>
int main() {
// Get CPU clock time before operation
clock_t start_time = clock();
// Perform some operation (e.g., a simple loop)
for (long i = 0; i < 1000000000; ++i);
// Get CPU clock time after operation
clock_t end_time = clock();
// Compute time difference
double duration = (double)(end_time - start_time) / CLOCKS_PER_SEC;
// Print time difference
printf("Elapsed time: %.6f seconds
", duration);
return 0;
}Sample output:
Elapsed time: 2.500000 secondsMeasuring Microseconds with gettimeofday()
#include <stdio.h>
#include <sys/time.h>
int main() {
struct timeval start, end;
// Get current time before operation
gettimeofday(&start, NULL);
// Perform some operation (e.g., a simple loop)
for (long i = 0; i < 1000000000; ++i);
// Get current time after operation
gettimeofday(&end, NULL);
// Compute time difference
double duration = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1e6;
// Print time difference
printf("Elapsed time: %.6f seconds
", duration);
return 0;
}Sample output:
Elapsed time: 2.499999 secondsKey Points
time() : returns seconds as an integer, low precision.
clock() : provides CPU time, higher precision.
gettimeofday() : offers microsecond precision.
Actual timings vary based on system performance and the workload.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
