[C language] Time calculation question. How to tell after 10 seconds.

Asked 2 years ago, Updated 2 years ago, 73 views

#include <stdio.h>
#include <time.h>
int main(void)
{
    time_t start, end;
    long i=0;
    double pst;
    start = time(NULL);
    while(i<30000000)
    {
        i++;
    }
    end=time(NULL);
    pst=difftime(end, start);
    printf("time: %f\n", pst);
    return 0;
}

Usually, to find the time difference, calculate the time when the code between start and end turns like the code above.

[Question]: I just wait 10 seconds without anything between start and end, and I say, "10 seconds have passed." I'd like to print out a sentence like this, is there a way? Waiting without doing anything.

c time

2022-09-20 21:54

1 Answers

Please refer to the code below.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <time.h>

int main()
{
    int second = 10;

    int sec_to_clocks = second * CLOCKS_PER_SEC;

    puts ("start");

    clock_t start_time = clock();

    while (clock() < start_time + sec_to_clocks)
        ;

    printf ("%d seconds have passed".\n", second);

    return 0;
}

Results


2022-09-20 21:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.