Determining process compute time is a common need in ISyE for such tasks as comparing algorithm efficiency. However, use of real time is likely to give erroneous results due to variations in compute environment, such as higher load and more context switching on some nodes than others. It is also possible that jobs can be suspended briefly without restarting from the beginning, which could greatly throw off compute times.

If you need to measure the compute time, you should use the USER time of the process to get the actual time it has been running on the processor.

In C, this value can be extracted with the getrusage() function.

The following example program runs three counting loops, but each subsequent step includes a longer sleep(). Nevertheless, the same elapsed time is reported for each step (within a millisecond). The function timeval_subtract() is taken from this GNU tutorial determining on elapsed CPU time.

#include 
#include 
#include  

int main() {
  int i, j, k;
  struct rusage usage;
  struct timeval current;
  struct timeval previous = {0, 0}; 

  for (i=0; itv_usec tv_usec) {
     int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
     y->tv_usec -= 1000000 * nsec;
     y->tv_sec += nsec;
  }
  if (x->tv_usec - y->tv_usec > 1000000) {
     int nsec = (x->tv_usec - y->tv_usec) / 1000000;
     y->tv_usec += 1000000 * nsec;
     y->tv_sec -= nsec;
  } 

  /* Compute the time remaining */
  /* tv_usec is certainly positive */
  result->tv_sec = x->tv_sec - y->tv_sec;
  result->tv_usec = x->tv_usec - y->tv_usec; 

 /* Return 1 if result is negative. */
  return x->tv_sec tv_sec;
}