Getting the CPU count

本文介绍了一种通过读取/proc/cpuinfo文件来获取Linux系统中CPU核心数量的方法,并提供了一个简洁的C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I managed to put this together, but I really don't like it. Is there possibly a more straightforward way to do this?

 

//LInux get cpu count

 


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 Dec 23, 2008 at 2:11amOct 15, 2010 at 6:26am UTC

engin (1)   Link to this post Dec 26, 2008 at 1:51pmOct 15, 2010 at 6:26am UTC

#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 :)

helios (7842)   Link to this post Dec 26, 2008 at 2:27pmOct 15, 2010 at 6:26am UTC
Well, it is shorter. It's not exactly what I had in mind, but at least it's elegant.
Thanks.

jwoolsto (36)   Link to this post Jan 10, 2009 at 11:03amOct 15, 2010 at 6:26am UTC
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.

Zaita (2113)   Link to this post Jan 12, 2009 at 3:22amOct 15, 2010 at 6:26am UTC
jwoolsto: That's an OSX question, it'll be either an API call or stored in a file on your file system.

jwoolsto (36)   Link to this post Jan 12, 2009 at 4:28amOct 15, 2010 at 6:26am UTC
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.

jwoolsto (36)   Link to this post Jan 13, 2009 at 5:56amOct 15, 2010 at 6:26am UTC
For the record:

http://forums.macosxhints.com/showthread.php?p=512843#post512843
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值