3

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

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
A. Sinha
  • 2,666
  • 3
  • 26
  • 45
  • @Blindy This solution talks about POSIX, will it not be different on windows machine? Correct me if I am wrong but clock() behaves differently on windows and on UNIX. – A. Sinha Aug 06 '20 at 15:26
  • 1
    If you're looking for a Windows only solution, you have `QueryPerformanceCounter`. You mentioned [c], but if you have access to C++ as well, the portable equivalent is the standard `chrono` library, which uses QPC internally in Windows.. – Blindy Aug 06 '20 at 15:32
  • I _voted to close_ before seeing the ***emphasis on Windows 7*** (edited in during my vote.) . The linked duplicate is specific to Linux and does not address this question. Am voting to reopen. – ryyker Aug 06 '20 at 15:40
  • 2
    `clock()` wraps around (like a real clock) so a time in the past can have a greater value than now (same as 4 hours before 2am is 10pm: `2 - 10 = -8` / `2 - 22 = -20`) – pmg Aug 06 '20 at 15:41
  • @pmg Assuming the OP uses (a compiler that uses) Windows' UCRT, `clock()` does not wrap around but rather [returns `-1`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/clock?view=vs-2019) once it hits `LONG_MAX` after 25 days or so. – dxiv Aug 06 '20 at 22:53
  • @Blindy The UCRT `clock()` on Windows uses QPC as well. – dxiv Aug 06 '20 at 22:58
  • the statement: `#include ` exposes the function: `difftime()`. the syntax is; `double difftime(time_t time1, time_t time0);` Using that function, you will not be getting negative elapsed time in your code, as the elapsed number of seconds. – user3629249 Aug 07 '20 at 21:07

1 Answers1

1

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.

sys101
  • 19
  • 3