2

Does CLOCKS_PER_SEC varies from system to system or is it constant for an operating system or is it dependent on the processor of that particular system?? And also do help me explain the output of my code...is it right??

#include<stdio.h>
#include<time.h>
int main()
{
int a;
long int b;
clock_t start, end;

start = clock();

//Code for which the time is to be calculated
for(a=0;;a++)
{
    if(a<0)
    {
        break;
    }
}
printf("int : %u\n",a);
for(b=0;;b++)
{
    if(b<0)
    {
        break;
    }
}
printf("long int :%u\n",b);
//code is over

end = clock();

//CLOCKS_PER_SECOND : the number of clock ticks per second
printf("Starting Time:%u\n",start);
printf("Ending Time:%u\n",end);
printf("CLOCKS_PER_SEC:%u",CLOCKS_PER_SEC);
printf("\nNumber of clock ticks:%u",(end - start));
printf("\nTotal time:%u",(double)(end - start)/CLOCKS_PER_SEC);
return 0;
}

output:

int : 2147483648
long int :2147483648
Starting Time:0
Ending Time:9073
CLOCKS_PER_SEC:1000
Number of clock ticks:9073
Total time:1099511628
Process returned 0 (0x0)   execution time : 15.653 s
Press any key to continue.
UltraRadiantx
  • 67
  • 2
  • 9
  • What do you think why it's defined as a macro? Of course, you should not assume it's the same on every system! –  Jul 24 '18 at 14:41
  • 1
    AFAIK, POSIX defines it to 1'000'000. So you seem to be on a non-POSIX system. –  Jul 24 '18 at 14:42
  • 3
    btw, `%u` is the wrong format specifier for printing a `double`. –  Jul 24 '18 at 14:46

1 Answers1

9

Does CLOCKS_PER_SEC varies from system to system or is it constant for an operating system or is it dependent on the processor of that particular system?

CLOCKS_PER_SEC is ultimately determined by the compiler and its standard library implementation, not the OS. Although the machine, OS and other factors contribute to what a compiler provides.

help me explain the output of my code...is it right?

No. printf("\nTotal time:%u",(double)(end - start)/CLOCKS_PER_SEC); is using "%u" to print a double. @Felix Palmen

CLOCKS_PER_SEC is not necessarily an unsigned.
clock_t is not necessarily an int. Ref
Using the wrong printf() specifiers renders the output uninformative.
Tip: enable all compiler warnings.

Cast to a wide type and use a matching print specifier.

clock_t start
// printf("Starting Time:%u\n",start);
printf("Starting Time:%g\n", (double) start);

// printf("CLOCKS_PER_SEC:%u",CLOCKS_PER_SEC);
printf("CLOCKS_PER_SEC:%g\n", (double) CLOCKS_PER_SEC);

// printf("\nTotal time:%u",(double)(end - start)/CLOCKS_PER_SEC);
printf("Total time:%g\n",(double)(end - start)/CLOCKS_PER_SEC);

Or even consider long double.

long double t = (long double)(end - start)/CLOCKS_PER_SEC;
printf("Total time:%Lg\n", t);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256