Cover Image for Simple Stopwatch Program in C
160 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:

  1. We declare variables start_time and end_time of type clock_t to store the start and end times.
  2. We use clock() to record the current CPU time when the user presses Enter to start and stop the stopwatch.
  3. We calculate the elapsed time by subtracting start_time from end_time and dividing by CLOCKS_PER_SEC to get the time in seconds.
  4. 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.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS