Shankhadeep Mukerji Shankhadeep Mukerji - 2 months ago 8
C Question

polling the number of clock cyclesw in C

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 now changed the code and still getting start:0.0000 and end=0.0000

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

Answer

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);
}