5

I am trying to measure the resource usage time (user and system) for various function calls using rusage. I find that the results I am getting are in the order of 10s of milliseconds like 0s 70000us, 10000us etc. Please let me know if there is a way to set precision/ granularity for getrusage.

My program is simple:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>

int main(){
  struct rusage usage;
  struct timeval start, end;
  int i, j, k = 0;

  getrusage(RUSAGE_SELF, &usage);
  start = usage.ru_utime;
  printf("buffer check\n");
  char *str = "---";
  int arr[100],ctr;

  for(ctr = 0;ctr<100;ctr++){

    arr[ctr] = ctr + 1000;

  }

  for (i = 0; i < 10000; i++) {
     for (j = 0; j < 10000; j++) {
      k += 20;
  }
 }

 getrusage(RUSAGE_SELF, &usage);
 end = usage.ru_utime;

 printf("Started at: %ld.%lds\n", start.tv_sec, start.tv_usec);
 printf("Ended at: %ld.%lds\n", end.tv_sec, end.tv_usec);

 return 1;
}

Result Started at: 0.0s Ended at: 0.2000000s

I added another for loop and got result like: Started at: 0.0s Ended at: 0.7000000s I browsed a lot to find a possible way to get accurate timings. Came across 3 parameter getrusage in linux sources etc. but I am not sure how to use it since it required the task pointer as the first param. One of the link suggested it has got to do with linux version. Regardless, please let me know if there is any way to set the precision/granularity. If not, let me know if there is any alternative to getrusage. gettimeofDay does not seem to give the resource usage details so looking for actual implementation of getrusage if somehow I am not able to set precision.

2
  • If you just want to measure the speed of your program, I suggest running your functions for a million times and watch the total time.
    – Logan Ding
    Sep 27, 2013 at 6:35
  • I found that if I run the same program in some other PC, it gives accurate results. Sep 27, 2013 at 6:56

3 Answers 3

4

Many operating systems don't do precise accounting of time used by processes. In many cases it's too expensive to read clocks on every context switch and system call, in other cases the hardware might not even have a clock that's allows you to time things with any precision.

A very commonly used method for accounting that you get from getrusage is to have a 100Hz (it's most often 100Hz, although 64Hz and 1024Hz are common too) timer interrupt that samples what's happening on the system at the time of the interrupt. So 100 times per second the kernel checks what is currently running and where (user space for ru_utime or kernel space for ru_stime) and increments a counter. That counter is then interpreted as your program running for 10ms.

You can experiment with clock_gettime on your system, see if it has per-process counters, sometimes those can be more precise than the getrusage counters. But I wouldn't get my hopes up, if 10ms resolution is the best getrusage can do, it's likely that clock_gettime won't have a better resolution either or any per-process clocks at all.

If the clocks in the operating system aren't good enough for your measurements your only option is to repeat your test run for several minutes and divide whatever result you get by the number of runs.

The fact that gettimeofday is more precise doesn't mean much. gettimeofday might be relatively expensive. Think about the work the kernel would have to do to accurately keep track of user and system time for a process. Every time you make a system call it would have to take a time stamp twice (one for the start of the system call and once at the end) just to keep track of how much system time you use. For keeping track of user time you'd need time stamps on every time the system switches to another process. Many systems do keep track of the second one, but not the first one since system calls are much more common than process context switches (that's why I suggest checking clock_gettime since it can have a timer that accumulates total system and user time for a process).

Clocks in modern systems are quite annoying because even though taking time stamps is one of the most common system calls we still often need to trawl through a slow bus and do heavy locking to get them. Other solutions like cycle counters on the cpu have been used but those are notoriously inaccurate because they might be not synchronized between CPUs, might have a variable frequency, can stop outside of the control of the operating system, etc. and you need to know the exact model of your CPU to be able to reliably use them. The operating system has a lot of heuristics to figure out which clocks to use, but it might mean that there's a huge difference between two machines that are almost the same. One might get a cycle counter with sub-nanosecond precision that costs one instruction to read while the other needs to go through the ISA bus to a 30 years old chip design with microsecond precision or worse which takes thousands of cycles to read.

8
  • Thanks Art! But when I use getTimeOfDay, i get the time in microseconds. Sep 29, 2013 at 0:40
  • @SaurabhGhorpade Expanded my answer to explain why gettimeofday doesn't necessarily correlate to the timers for getrusage.
    – Art
    Sep 30, 2013 at 7:35
  • Thanks again, Art! As you said, I tried clock_gettime, but have not got the expected results. The numbers coming for whatever parameters I pass as clk ID, all the results appear to be same. And it is same as results returned by getTimeOfDay. I wonder if clock_getTime is different from getTimeOfDay. Oct 1, 2013 at 4:04
  • I have posted my new program with the results as a reply to my question. Please have a look. Oct 1, 2013 at 4:17
  • Various clocks returned by clock_gettime measure different things. PROCESS and THREAD clocks should be the same with one thread. They start at the start of your process and a second should correspond to an SI second as close as your system can get. They start and stop whenever your process starts and stop. MONOTONIC clock has an SI second and a zero point at some undefined point in time. REALTIME is the same as gettimeofday and it can have seconds shorter or longer than an SI second depending on how ntp adjusts the time on your system. For your measuring use PROCESS.
    – Art
    Oct 1, 2013 at 7:35
0
My new program:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
//int clock_gettime(clockid_t clk_id, struct timespect *tp);

#define BILLION  1000000000L;

void testClockGetTime(clockid_t clk_id , struct timespec *start , struct timespec  *stop){

   long temp = 0,i;
   unsigned long accumsec,accumns;
   if( clock_gettime( clk_id, start) == -1 ) {
      perror( "clock gettime" );
      exit( EXIT_FAILURE );
   }
   for ( i = 0; i< 24222000; i++)
       temp+=temp;

   if( clock_gettime( clk_id, stop) == -1 ) {
      perror( "clock gettime" );
      exit( EXIT_FAILURE );
    }
    accumsec = stop->tv_sec - start->tv_sec;
    accumns =  stop->tv_nsec - start->tv_nsec;
    if(stop->tv_nsec<start->tv_nsec){
       accumsec = accumsec - 1;
       accumns = start->tv_nsec - stop->tv_nsec;
    }

    printf( " sec %ld\n", accumsec );
    printf(" ns %ld\n", accumns );

  }

int main( int argc, char **argv )
 {
   struct timespec start, stop;
   struct timeval tds,tdse;
   memset(&tds,0,sizeof(struct timeval));
   memset(&tdse,0,sizeof(struct timeval));
   unsigned long accumsec,accumns;
   long timesec, timeusec;
   printf("checking on various timers gives by clockGetTime \n");
   printf("cpu time\n");
   memset(&stop,0,sizeof(struct timespec));
   memset(&start,0,sizeof(struct timespec));
   testClockGetTime(CLOCK_PROCESS_CPUTIME_ID , &start,&stop);
   memset(&start,0,sizeof(struct timespec));
   memset(&stop,0,sizeof(struct timespec));
   printf("real time\n");    
   testClockGetTime(CLOCK_REALTIME,&start,&stop);
   memset(&start,0,sizeof(struct timespec));
   memset(&stop,0,sizeof(struct timespec));
   printf("monotonic\n");    
   testClockGetTime(CLOCK_MONOTONIC,&start,&stop);
   memset(&start,0,sizeof(struct timespec));
   memset(&stop,0,sizeof(struct timespec));
   printf("thread\n");
   testClockGetTime(CLOCK_THREAD_CPUTIME_ID,&start,&stop);
   memset(&start,0,sizeof(struct timespec));
   memset(&stop,0,sizeof(struct timespec));
   gettimeofday(&tds, NULL);
   long temp,i;
   for ( i = 0; i< 24222000; i++)
      temp+=temp;
   gettimeofday(&tdse, NULL);
   if( clock_gettime( CLOCK_PROCESS_CPUTIME_ID, &stop) == -1 ) {
      perror( "clock gettime" );
      exit( EXIT_FAILURE );
    }

    //   accumsec = stop.tv_sec - start.tv_sec; 
    //   accumns =  stop.tv_nsec - start.tv_nsec; 
    //   if(stop.tv_nsec<start.tv_nsec){
    //     accumsec = accumsec - 1;
    //     accumns = start.tv_nsec - stop.tv_nsec;
    //   }

    //   printf( "proc sec %ld\n", accumsec );
    //   printf( "proc ns %ld\n", accumns );
    //    printf("before day =%ld,%ld\n",tds.tv_sec,tds.tv_usec);
    //    printf("after day=%ld,%ld\n",tdse.tv_sec, tdse.tv_usec);
    timesec =  tdse.tv_sec - tds.tv_sec;
    timeusec=  tdse.tv_usec- tds.tv_usec;
  if(tdse.tv_usec < tds.tv_usec){
    timesec = timesec - 1;
    timeusec= tds.tv_usec - tdse.tv_usec;
   }
   printf("daytime sec =%ld\n",timesec);
   printf("daytime usec=%ld\n",timeusec);
   return( EXIT_SUCCESS );
 }

Results:

first run > gcc getclk.c -o dfkj -lrt

getclk.c: In function 'main':

getclk.c:40: warning: incompatible implicit declaration of built-in function 'memset'

./dfkj

checking on various timers gives by clockGetTime

cpu time

sec 0

ns 54502537

real time

sec 0

ns 53748970

monotonic

sec 0

ns 55456758

thread

sec 0

ns 58649229

daytime sec =0

daytime usec=56991

second run>./dfkj

checking on various timers gives by clockGetTime

cpu time

sec 0

ns 54220021

real time

sec 0

ns 52774966

monotonic

sec 0

ns 53636163

thread

sec 0

ns 53357492

daytime sec =0

daytime usec=56176

0

On 2013-10-01 4:48 PM, Saurabh wrote:

Hi Douglas, I am Saurabh. I saw your responses at stack overflow . Somehow when I run getrusage, it does not give results in microseconds. But in milliseconds. Please let me know if you have a fix for this. Else kindly suggest me API to replace getrusage.

Yes, getrusage has ms precision on my Linux system as well. It returns with µs precision only on my OS X workstation. It says this in my post that you reference, if you look carefully: "The precision on my system is 1 µs, but I also tested it on a Linux system (Red Hat 4.1.2-48 with GCC 4.1.2) and there the precision was only 1 ms."

With regards to your request of an alternate function, I agree with Art. As far as I know, clock_getTime provides by far the best clocks for Linux. The only issue is that it's relatively new, so it's not very portable (OS X doesn't have it, for example). Nevertheless, if you want precise timing and you're using Linux, I recommend clock_gettime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.