TransWikia.com

clock() returning negative time difference on Windows machine

Stack Overflow Asked by A. Sinha on December 3, 2020

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).

One Answer

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.

Answered by sys101 on December 3, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP