CUBRID Engine  latest
get_clock_freq.c
Go to the documentation of this file.
1 /*
2  * Copyright 2008 Search Solution Corporation
3  * Copyright 2016 CUBRID Corporation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 /*
20  * get_clock_freq.c - get_clock_freq() function implementation
21  */
22 
23 #ident "$Id$"
24 
25 #include "config.h"
26 
27 #include <fcntl.h>
28 #include <stdlib.h>
29 #include "tsc_timer.h"
30 
31 /*
32  * get_clock_freq() - get the CPU clock rate
33  * return: the CPU or Mainboard clock rate (KHz)
34  */
37 {
38 #if defined (WINDOWS)
39  /*
40  * Note: It has been implemented for Windows.
41  */
42  LARGE_INTEGER fr;
43  QueryPerformanceFrequency (&fr);
44  return (TSC_UINT64) fr.QuadPart;
45 
46 #elif defined (LINUX)
47  /* We read the information from the /proc filesystem. It contains at least one line like cpu MHz : 497.840237 or
48  * also cpu MHz : 497.841 We search for this line and convert the number in an integer. */
49  TSC_UINT64 clock_freq = 0;
50  int fd;
51  char buf[4096], hz[32];
52  char *src, *dest, *ovf, *dp = NULL;
53  ssize_t n;
54 
55  fd = open ("/proc/cpuinfo", O_RDONLY);
56  if (fd == -1)
57  {
58  goto exit;
59  }
60 
61  n = read (fd, buf, sizeof (buf));
62  if (n <= 0)
63  {
64  goto exit;
65  }
66 
67  ovf = buf + n;
68 
69  src = strstr (buf, "cpu MHz");
70  if (src == NULL)
71  {
72  goto exit;
73  }
74 
75  dest = hz;
76 
77  while (*src != '\n')
78  {
79  if (*src < '0' || *src > '9')
80  {
81  if (*src == '.')
82  {
83  dp = dest;
84  }
85 
86  src++;
87  }
88  else
89  {
90  *dest++ = *src++;
91  }
92 
93  if (src >= ovf)
94  {
95  goto exit;
96  }
97  }
98 
99  if (dp == NULL)
100  {
101  dp = dest;
102  }
103 
104  while ((dest - dp) < 6)
105  {
106  *dest++ = '0';
107  }
108 
109  *dest = '\0';
110 
111  clock_freq = strtoull (hz, NULL, 10);
112  if (clock_freq == 0)
113  {
114  goto exit;
115  }
116 
117 exit:
118 
119  if (fd != -1)
120  {
121  close (fd);
122  }
123 
124  return clock_freq;
125 
126 #else
127  /*
128  * Note: Unknown OS. the return value will not be used.
129  */
130  return 1;
131 
132 #endif
133 }
UINT64 TSC_UINT64
Definition: tsc_timer.h:39
#define NULL
Definition: freelistheap.h:34
TSC_UINT64 get_clock_freq(void)