getrusage vs clock

paul zimmermann Paul.Zimmermann at inria.fr
Mon Jan 18 15:07:14 UTC 2016


       Dear GMP developers,

since version 2.18 of the glibc, the clock() function is much more precise.
For example on my machine it has a resolution of 1 micro-seconds whereas
getrusage() has a resolution of 4ms only, as demonstrated by the program
below:

zimmerma at tomate:~/try$ ./a.out 
GNU libc version: 2.21
GNU libc release: stable
loops=3512013 clock=1000662 getrusage=1000000 nb_clock=1000000 nb_getrusage=250
resolution clock = 1.00us
resolution getrusage = 4000.00us

I therefore suggest to replace getrusage() by clock() in speed/tune.

Paul

#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <gnu/libc-version.h>

unsigned long
time_clock ()
{
  return clock ();
}

unsigned long
time_getrusage ()
{
  struct rusage rus;
  getrusage (0, &rus);
  return rus.ru_utime.tv_sec * 1000000 + rus.ru_utime.tv_usec
    + rus.ru_stime.tv_sec * 1000000 + rus.ru_stime.tv_usec;
}

int
main()
{
  unsigned long t_clock, t_getrusage;
  unsigned long last_clock, last_getrusage;
  unsigned long nb_clock = 0, nb_getrusage = 0, loops = 0;

  printf("GNU libc version: %s\n", gnu_get_libc_version ());
  printf("GNU libc release: %s\n", gnu_get_libc_release ());
  last_clock = time_clock ();
  last_getrusage = time_getrusage();
  while (nb_clock < 1000000 && nb_getrusage < 1000000)
    {
      t_clock = time_clock ();
      nb_clock += t_clock != last_clock;
      last_clock = t_clock;

      t_getrusage = time_getrusage ();
      nb_getrusage += t_getrusage != last_getrusage;
      last_getrusage = t_getrusage;

      loops ++;
    }
  printf ("loops=%lu clock=%lu getrusage=%lu nb_clock=%lu nb_getrusage=%lu\n",
          loops, time_clock (), time_getrusage (), nb_clock, nb_getrusage);
  printf ("resolution clock = %.2fus\n", (double) time_clock () / nb_clock);
  printf ("resolution getrusage = %.2fus\n", (double) time_getrusage () / nb_getrusage);
}




More information about the gmp-devel mailing list