4

I am curious to know why does the function clock() only returns values in increments of 10,000 and is not able to return values in between.

I have the following code:

#include<iostream>
#include<time.h>
#include<stdio.h>
using namespace std;

int main()
{
    int a;
    clock_t clock_start;
    time_t start1;
    time(&start1);
    clock_start = clock();

    for(int i=0;i<200000;i++)
        cout<<8;

    time_t end1;
    time(&end1);

    clock_t clock_end = clock();

    int b;
    printf("\n\n%d",end1-start1);
    printf("\nClock ticks ?? = %d",clock_end-clock_start);
    return 0;
}

The result is either 0 or 10,000

There is no in-between.

The same situation is happening even if I modify the number of iterations the 'for' loop runs. The values are also multiple of 10,000

What is the reason behind this behavior and what is a practical use case for the "clock" function in this case? It seems quite unreliable to me.

11
  • 2
    Just like thread scheduling, this kind of clock function only gets incremented every couple of milliseconds (on windows it varies between 0.5 and 16ms, depending on applications having requested shorter ticks). If you want precision timing, use high precision functions, like Windows's QueryPerformanceCounter. Oct 12, 2017 at 14:36
  • @CodesInChaos It is actually incremented every second which I find actually ridiculous.... I am running Linux on x86
    – yoyo_fun
    Oct 12, 2017 at 14:38
  • 1
    Try clock_gettime() instead. linux.die.net/man/3/clock_gettime. Oct 12, 2017 at 14:48
  • 1
    See also this Stack Overflow question. The OP has code nearly identical to yours. Oct 12, 2017 at 14:56
  • 2
    FYI, clock() doesn't report wall-clock time, it reports CPU time, and you're also not using the CLOCKS_PER_SEC constant. Oct 12, 2017 at 15:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.