pylearner
pylearner

Reputation: 63

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.

Upvotes: 4

Views: 4052

Answers (3)

ralight
ralight

Reputation: 11608

You could try using clock_gettime() with the CLOCK_PROCESS_CPUTIME_ID option if you are on a POSIX system. clock_gettime() uses struct timespec to return time information so doesn't suffer from the same problem as using a single integer.

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

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.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224844

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

Upvotes: 6

Related Questions