
259 views
Simple Stopwatch Program in C
Creating a simple stopwatch program in C involves measuring the time elapsed between the start and stop events. You can use the clock()
function from the <time.h>
header to accomplish this. Here’s a basic example:
C
#include <stdio.h>
#include <time.h>
int main() {
clock_t start_time, end_time;
double elapsed_time;
printf("Press Enter to start the stopwatch...");
getchar(); // Wait for user to press Enter
start_time = clock(); // Record the start time
printf("Stopwatch is running. Press Enter to stop...");
getchar(); // Wait for user to press Enter again
end_time = clock(); // Record the end time
// Calculate the elapsed time in seconds
elapsed_time = (double)(end_time - start_time) / CLOCKS_PER_SEC;
printf("Elapsed time: %.2f seconds\n", elapsed_time);
return 0;
}
In this program:
- We declare variables
start_time
andend_time
of typeclock_t
to store the start and end times. - We use
clock()
to record the current CPU time when the user presses Enter to start and stop the stopwatch. - We calculate the elapsed time by subtracting
start_time
fromend_time
and dividing byCLOCKS_PER_SEC
to get the time in seconds. - Finally, we display the elapsed time.
Compile and run the program, and it will act as a basic stopwatch. The user presses Enter to start and stop the stopwatch, and the program calculates and displays the elapsed time in seconds.
Please note that this stopwatch measures CPU time, which may not be the same as real-time elapsed in some cases, especially on multi-core systems. For accurate real-time measurements, you may need to use system-specific functions or libraries.