0

I am trying to continuously poll the number of clock cycles ticked and print my statement only when the cycle count is 100 + the start time . Such that if my start = 1000000, the print statement should be executed only when end = 1000100 and it should show e.g assuming at start, time = 1000000 Hello, value of start:1000000 and value of end:1000101

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

void main()
{
        clock_t start,end;
        start = clock();
        while(end=clock() < (start + 100))
        {};
        printf("Hello, value of start:%d and value of end:%d", start, end);
}

However I am getting Hello, value of start:0 and value of end:0

I have edited my code and getting value of end=0.0000. This is my edited code below

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

void main()
{
        clock_t start;
        start = clock();
        clock_t end = start;
        printf("Hello");
        while(end < (start + 100))
        {
                end = clock();
        };
        printf("value of end is %f \n", end);
}

3 Answers3

1

I'm pretty sure this line:

while(end=clock()< start + 100)

Needs to be this:

while( (end=clock()) < (start + 100) )

Written better:

void main()
{
        clock_t start = clock();
        clock_t end = start;
        while(end < (start + 100))
        {
            end = clock();
        };
        printf("Hello, value of start:%d and value of end:%d", (int)start, (int)end);
}
selbie
  • 100,020
  • 15
  • 103
  • 173
  • I am getting this output now after following the above Hello, value of start:0 and value of end:-1582571616. But I waqnt end to be 100 – Shankhadeep Mukerji Oct 03 '16 at 01:15
  • 1
    I suspect clock_t is really a 64-bit type, long, or something else. Update the format specifiers in your printf statement. – selbie Oct 03 '16 at 01:17
1

while(end=clock()< start + 100)

is incorrect, because = has lower precedence than <.

To be precise your statement would be interpreted like this (note the order of precedence: + then < then =):

while( end = ( clock() < ( start + 100 ) ) )
    ;

( clock() < ( start + 100 ) ) is a Boolean expression that will be either 1 or 0; your while loop runs until the condition becomes wrong which means ( clock() < ( start + 100 ) ) is 0, which is then assigned to end.

So don't be hesitant to put extra brackets in the expression. In this case, what you need is:

while( ( end=clock() ) < start + 100)
    ;
artm
  • 17,291
  • 6
  • 38
  • 54
1

The first problem is as other have said that the precedence in the if condition is wrong. The second is that clock_t isn't necessarily expressible as an integer. Best bet is to cast to double, which will give enough range in the common case that clock_t is a 64 bit integer but the values relatively small.

Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18