Getting the CPU count

I managed to put this together, but I really don't like it. Is there possibly a more straightforward way to do this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
ushort getCPUcount(){
    std::ifstream cpuinfo("/proc/cpuinfo");
    std::string line;
    /*
    I read somewhere that the processor ID could be repeated. I don't know if
    that's true or not.
    */
    std::set<unsigned> IDs;
    while (!cpuinfo.eof()){
        std::getline(cpuinfo,line);
        if (!line.size())
            continue;
        if (line.find("processor")!=0)
            continue;
        size_t start=line.find(':'),
            end;
        for (;line[start]<'0' || line[start]>'9';start++);
        for (end=start;line[end]>='0' && line[end]<='9';end++);
        line=line.substr(start,end-start);
        IDs.insert(atoi(line.c_str()));
    }
    return IDs.size();
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include "stdio.h"

using namespace std;

int main(){
        FILE * fp;
        char res[128];
        fp = popen("/bin/cat /proc/cpuinfo |grep -c '^processor'","r");
        fread(res, 1, sizeof(res)-1, fp);
        fclose(fp);
        cout << "number of core: " << res[0] << endl;
        return 0;
}


good luck :)
Well, it is shorter. It's not exactly what I had in mind, but at least it's elegant.
Thanks.
I don't suppose anyone would be willing to help me find that file on OSX? There is no proc directory in my root directory.
jwoolsto: That's an OSX question, it'll be either an API call or stored in a file on your file system.

Zaita: I posted on an osx forum as well, but I figured the odds were decent at least I wasn't the only one here programming on osx so I thought it was worth a shot.
Topic archived. No new replies allowed.