Hello, i was wondering if i could get an opinion on the following code as it is giving me a headache:

``````    int counter = 498853097;
int k = 0;

clock_t start, end;
float seconds1,seconds2;

start = clock();
for (int i = 0; i < counter; i++)
{
k++;
}
end = clock();
seconds2 = (float)(end - start) / CLOCKS_PER_SEC;

start = clock();
for (int i = 0; i < counter; i++);
end = clock();
seconds1 = (float)(end - start) / CLOCKS_PER_SEC;

printf("\n Time 2 [%f]  -  Time 1 [%f] = %f",seconds2,seconds1,seconds2-seconds1);
``````

It's the exact same repetition twice, except one of them has an integer increment.
The result i'm getting is negative every time, eg
Time 2 [0.877000] - Time 1 [0.955000] = -0.078000. What am i missing?

What optimisation level are you building the code with? In both those loops, there is a significant amount of work that a good compiler will simply not bother doing. If you build it at the lowest level of optimisation, you might see a different result.

What that invites you to do, of course, is take a look at the assembly code generated at low and high optimisation to see what's really going on.

Thanks a lot for your answer you rule. What i am trying to do is: repeat external (example 1000 times ,doesnt matter): run the internal repeat (the one that is counted by seconds2) plus function A. Again the same with function B. What im trying to find is the time difference that the 2 functions A and B have, counted in real time. For example,

``````    start = clock();
end = clock();
seconds2 = (float)(end - start) / CLOCKS_PER_SEC;
while (seconds<10){
for (int i = 0; i < counter; i++)
{
k++;
}
myFunctionA();
end = clock();
seconds2 = (float)(end - start) / CLOCKS_PER_SEC;
}
``````

and the same with myFunctionB(). The data results i have is the real time (10 sec) plus the number k reached. What i want is to determine how much real time-delay did myFuncA/B cause. The first step to determine that was to try to time just the repetition and then the repeat+increment so im getting nowhere. Thanks for your time anyway.