简体   繁体   中英

Why does clock() produce inconsistent intervals between sleep()?

I think the output of following code should be excatly or near the macro CLOCKS_PER_SEC, however, the output is not very consistant.

int main(int argc, char const *argv[])
{
    clock_t before = clock();

    while (1) {
        sleep(1);
        printf("Res: %ld\n", clock() - before);
        fflush(stdout);
        before = clock();
    }
}

Sample Output:

Res: 0
Res: 1301
Res: 1540
Res: 1597
Res: 1631
Res: 1689
Res: 1740
Res: 1783
Res: 1835
Res: 1902
Res: 1956
Res: 1981
Res: 2045
Res: 2098
Res: 2147
Res: 2207
Res: 2265
Res: 2323

I assume the clock() function only return the excution time of the code.

So, How can I measure real world time in c?

From the documentation:

The value returned is the CPU time used so far as a clock_t; to get the number of seconds used, divide by CLOCKS_PER_SEC. If the processor time used is not available or its value cannot be represented, the function returns the value (clock_t) -1.

So the output shows the time the processor was used. Since sleep does not do a busy wait, much less than a second is used on the processor.

For getting real elapsed time see for example How do I measure a time interval in C?

There is no way to measure elapsed time with better than one second resolution in the C standard.

One popular non-standard function is gettimeofday from POSIX. It is good for obtaining current wall clock time with 1 ms resolution. It does not come standard on Windows but free implementations for that platform are easy to find.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM