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

Related Questions

SQL Query for Pagination

1  Asked on November 12, 2021 by abbas


Android. Invisible Top Bar

2  Asked on November 12, 2021 by sb69lg


loop does not iterate over list

1  Asked on November 12, 2021 by ripj


Grouping data by week

3  Asked on November 12, 2021 by beefstu


Does changing state cause re-render in ReactJS

1  Asked on November 12, 2021 by coderocks


Split a long string into full sentences in R

1  Asked on November 12, 2021 by jenifav


What is n= n ^1U<<i?

2  Asked on November 10, 2021 by akshayroy


What is the excel formula for within the next 7 business days?

2  Asked on November 10, 2021 by gradstud


Shuffle certain items in python array

3  Asked on November 10, 2021 by david-ferris


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir