Back to index

glibc  2.9
Functions
get_clockfreq.c File Reference
#include <ctype.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <libc-internal.h>
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

hp_timing_t __get_clockfreq (void)

Function Documentation

Definition at line 28 of file get_clockfreq.c.

{
  /* We read the information from the /proc filesystem.  It contains at
     least one line like
       cpu MHz         : 497.840237
     or also
       cpu MHz         : 497.841
     We search for this line and convert the number in an integer.  */
  static hp_timing_t result;
  int fd;

  /* If this function was called before, we know the result.  */
  if (result != 0)
    return result;

  fd = open ("/proc/cpuinfo", O_RDONLY);
  if (__builtin_expect (fd != -1, 1))
    {
      /* XXX AFAIK the /proc filesystem can generate "files" only up
         to a size of 4096 bytes.  */
      char buf[4096];
      ssize_t n;

      n = read (fd, buf, sizeof buf);
      if (__builtin_expect (n, 1) > 0)
       {
         char *mhz = memmem (buf, n, "cpu MHz", 7);

         if (__builtin_expect (mhz != NULL, 1))
           {
             char *endp = buf + n;
             int seen_decpoint = 0;
             int ndigits = 0;

             /* Search for the beginning of the string.  */
             while (mhz < endp && (*mhz < '0' || *mhz > '9') && *mhz != '\n')
              ++mhz;

             while (mhz < endp && *mhz != '\n')
              {
                if (*mhz >= '0' && *mhz <= '9')
                  {
                    result *= 10;
                    result += *mhz - '0';
                    if (seen_decpoint)
                     ++ndigits;
                  }
                else if (*mhz == '.')
                  seen_decpoint = 1;

                ++mhz;
              }

             /* Compensate for missing digits at the end.  */
             while (ndigits++ < 6)
              result *= 10;
           }
       }

      close (fd);
    }

  return result;
}

Here is the call graph for this function: