2.9
[glibc/nacl-glibc.git] / sysdeps / unix / sysv / linux / i386 / get_clockfreq.c
blob3e2b18392c931385fb94ff90e046c63bdab1f3fa
1 /* Get frequency of the system processor. i386/Linux version.
2 Copyright (C) 2000, 2001 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 02111-1307 USA. */
20 #include <ctype.h>
21 #include <fcntl.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <libc-internal.h>
27 hp_timing_t
28 __get_clockfreq (void)
30 /* We read the information from the /proc filesystem. It contains at
31 least one line like
32 cpu MHz : 497.840237
33 or also
34 cpu MHz : 497.841
35 We search for this line and convert the number in an integer. */
36 static hp_timing_t result;
37 int fd;
39 /* If this function was called before, we know the result. */
40 if (result != 0)
41 return result;
43 fd = open ("/proc/cpuinfo", O_RDONLY);
44 if (__builtin_expect (fd != -1, 1))
46 /* XXX AFAIK the /proc filesystem can generate "files" only up
47 to a size of 4096 bytes. */
48 char buf[4096];
49 ssize_t n;
51 n = read (fd, buf, sizeof buf);
52 if (__builtin_expect (n, 1) > 0)
54 char *mhz = memmem (buf, n, "cpu MHz", 7);
56 if (__builtin_expect (mhz != NULL, 1))
58 char *endp = buf + n;
59 int seen_decpoint = 0;
60 int ndigits = 0;
62 /* Search for the beginning of the string. */
63 while (mhz < endp && (*mhz < '0' || *mhz > '9') && *mhz != '\n')
64 ++mhz;
66 while (mhz < endp && *mhz != '\n')
68 if (*mhz >= '0' && *mhz <= '9')
70 result *= 10;
71 result += *mhz - '0';
72 if (seen_decpoint)
73 ++ndigits;
75 else if (*mhz == '.')
76 seen_decpoint = 1;
78 ++mhz;
81 /* Compensate for missing digits at the end. */
82 while (ndigits++ < 6)
83 result *= 10;
87 close (fd);
90 return result;