explicit void declaration, remove unused arg. thanks ccomp
[mkp224o.git] / cpucount.c
blob20462da5c2f17994910bb4e8def8f656c51a22b2
1 #include "cpucount.h"
3 #ifndef BSD
4 # ifndef __linux__
5 // FreeBSD
6 # ifdef __FreeBSD__
7 # undef BSD
8 # define BSD
9 # endif
10 // OpenBSD
11 # ifdef __OpenBSD__
12 # undef BSD
13 # define BSD
14 # endif
15 // NetBSD
16 # ifdef __NetBSD__
17 # undef BSD
18 # define BSD
19 # endif
20 // DragonFly
21 # ifdef __DragonFly__
22 # undef BSD
23 # define BSD
24 # endif
25 # endif // __linux__
26 // sys/param.h may have its own define
27 # ifdef BSD
28 # undef BSD
29 # include <sys/param.h>
30 # define SYS_PARAM_INCLUDED
31 # ifndef BSD
32 # define BSD
33 # endif
34 # endif
35 #endif // BSD
37 #ifdef BSD
38 # ifndef SYS_PARAM_INCLUDED
39 # include <sys/param.h>
40 # endif
41 # include <sys/sysctl.h>
42 #endif
44 #include <unistd.h>
45 #include <string.h>
46 #include <stdio.h>
48 #ifdef __linux__
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <strings.h>
52 static int parsecpuinfo()
54 unsigned char cpubitmap[128];
56 memset(cpubitmap,0,sizeof(cpubitmap));
58 FILE *f = fopen("/proc/cpuinfo","r");
59 if (!f)
60 return -1;
62 char buf[8192];
63 while (fgets(buf,sizeof(buf),f)) {
64 // we don't like newlines
65 for (char *p = buf;*p;++p) {
66 if (*p == '\n') {
67 *p = 0;
68 break;
71 // split ':'
72 char *v = 0;
73 for (char *p = buf;*p;++p) {
74 if (*p == ':') {
75 *p = 0;
76 v = p + 1;
77 break;
80 // key padding
81 size_t kl = strlen(buf);
82 while (kl > 0 && (buf[kl - 1] == '\t' || buf[kl - 1] == ' ')) {
83 --kl;
84 buf[kl] = 0;
86 // space before value
87 if (v) {
88 while (*v && (*v == ' ' || *v == '\t'))
89 ++v;
91 // check what we need
92 if (strcasecmp(buf,"processor") == 0 && v) {
93 char *endp = 0;
94 long n = strtol(v,&endp,10);
95 if (endp && endp > v && n >= 0 && n < sizeof(cpubitmap) * 8)
96 cpubitmap[n / 8] |= 1 << (n % 8);
100 fclose(f);
102 // count bits in bitmap
103 int ncpu = 0;
104 for (size_t n = 0;n < sizeof(cpubitmap) * 8;++n)
105 if (cpubitmap[n / 8] & (1 << (n % 8)))
106 ++ncpu;
108 return ncpu;
110 #endif
112 int cpucount(void)
114 int ncpu;
115 #ifdef _SC_NPROCESSORS_ONLN
116 ncpu = (int)sysconf(_SC_NPROCESSORS_ONLN);
117 if (ncpu > 0)
118 return ncpu;
119 #endif
120 #ifdef __linux__
121 // try parsing /proc/cpuinfo
122 ncpu = parsecpuinfo();
123 if (ncpu > 0)
124 return ncpu;
125 #endif
126 #ifdef BSD
127 const int ctlname[2] = {CTL_HW,HW_NCPU};
128 size_t ctllen = sizeof(ncpu);
129 if (sysctl(ctlname,2,&ncpu,&ctllen,0,0) < 0)
130 ncpu = -1;
131 if (ncpu > 0)
132 return ncpu;
133 #endif
134 return -1;