2

I am using timeval as well as clock() function to see the time difference between 2 actions in my c program. Somehow timeval seems to give me the right amount of elapsed time in milliseconds where clock() gives very very less value.

    g_time = clock();
    gettimeofday(&decode_t,NULL);

after sometime

    delay =((float)(clock()-g_time)/(float)CLOCKS_PER_SEC);
    gettimeofday(&poll_t,NULL);
    delay1 = ((poll_t.tv_sec - decode_t.tv_sec)*1000 + (poll_t.tv_usec -  decode_t.tv_usec)/1000.0)    ;
    printf("\ndelay1: %f delay: %f ",delay1,delay);

usual output is:

delay1: 1577.603027 delay: 0.800000

delay1 is in milliseconds and delay is in sec.

Iam using archlinux 64 bit.I can't understand why this is happening.

Gaurav Kumar
  • 153
  • 10

1 Answers1

2

From the clock(3) manual page:

The clock() function returns an approximation of processor time used by the program.

So the clock function doesn't return the amount of time passed, but a number of "ticks" that your program have run. And as you know, in a multi-tasking system your program can be paused at any time to let other programs run.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks for the reply but I am dividing the difference between ticks with CLOCKS_PER_SEC, which should give the elapsed time.Similarily, I am taking difference in time using timeval. Can I assume that time elapsed using clock() function gives the output which is exactly less by the amount of (ticks/CLOCKS_PER_SEC) when the programs was sleeping? – Gaurav Kumar Sep 10 '13 at 15:33
  • You program doesn't need to be sleeping to not accumulate processor time. For example, on a dual-core system, if you have more than two processes total in the system trying to run, each will be periodically suspended to allow another to run. – DoxyLover Sep 10 '13 at 17:08
  • @GauravKumar The important thing here is "processor time", which is the time your process is actually running. If your process is pre-empted (which it probably is several times per second) to run other processes, then that time does not count. The `clock` function is okay to measure run-time of your program, but not actual real time elapsed. – Some programmer dude Sep 10 '13 at 17:56
  • @JoachimPileborg Thanks a lot. I got it now. – Gaurav Kumar Sep 10 '13 at 18:46