A. Sinha
A. Sinha

Reputation: 2716

clock() returning negative time difference on Windows machine

I wrote following program in C to calculate the execution time (On a Windows-7 machine):

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

int main(void) {
double time_spent = 0.0;
clock_t begin;
clock_t end;

begin = clock();
    // code to read a file 
end = clock();
time_spent += ((double)(end - begin)) / CLOCKS_PER_SEC;

printf("Time elapsed is %f seconds", time_spent);
getch();
return 0;
}

At the end of the execution, the value of the (end-begin) is negative. Also, the value of begin was 46 while that of end was 43 after the program execution.

I am using a 64-bit Windows-7.

  1. Can someone please explain why the value of end is smaller than begin.
  2. How can this be fixed on a windows machine.

(clock() returning a negative value in C talks about POSIX only).

Upvotes: 3

Views: 322

Answers (1)

sys101
sys101

Reputation: 29

In windows 7 there are a whole series of clocks and interval timers available, both physical and via interfaces. Exactly which cpu(s)??? Certain time/timer functions WILL appear to run backwards!!! At least for short intervals/resolutions. This is a well known issue. See the Mircosoft web stuff. You probably want the win32 API interval timers, at a guess.

Upvotes: 1

Related Questions