Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clock() returning a negative value in C

I'm using a quite simple code to measure for time of execution.It works well until I am not sure may be not more than 20 minutes.But after(>20min.)it is returning negative results.I searched throughout the forums and tried everything like changing the datatype,using long unsigned (which is returning 0) but failed again. The following is the snippet of my code

main()
{
    time_t start,stop;
    double time_arm;
    start = clock(); 
    /* .......  */
    stop = clock();
    time_arm=(double)(stop-start)/(double)CLOCKS_PER_SEC;

    printf("Time Taken by ARM only is %lf \n",time_arm);
}

output is Time Taken by ARM only is -2055.367296

Any help is appreciated,thanks in advance.

like image 912
pylearner Avatar asked Feb 16 '23 00:02

pylearner


2 Answers

POSIX requires CLOCKS_PER_SEC to be 1,000,000. That means your count is in microseconds - and 231 microseconds is about 35 minutes. Your timer is just overflowing, so you can't get meaningful results when that happens.

Why you see the problem at 20 minutes, I'm not sure - maybe your CLOCKS_PER_SEC isn't POSIX-compatible. Regardless, your problem is timer overflow. You'll need to handle this problem in a different way - maybe look into getrusage(2).

like image 134
Carl Norum Avatar answered Feb 23 '23 16:02

Carl Norum


clock_t is long which is a 32-bit signed value - it can hold 2^31 before it overflows. On a 32-bit system the CLOCKS_PER_SEC value is equal to 1000000 [as mentioned by POSIX] clock() will return the same value almost after every 72 minutes.

According to MSDN also it can return -1.

The elapsed wall-clock time since the start of the process (elapsed time in seconds times CLOCKS_PER_SEC). If the amount of elapsed time is unavailable, the function returns –1, cast as a clock_t.

On a side note:-

clock() measures CPU time used by the program and it does NOT measure real time and clock() return value is specified in microseconds.

like image 27
Rahul Tripathi Avatar answered Feb 23 '23 18:02

Rahul Tripathi