# the number of online cpu



## luo (Oct 10, 2011)

How can I count the online number of CPU in kernel space?


----------



## SirDice (Oct 10, 2011)

```
sysctl hw.ncpu
```


----------



## DutchDaemon (Oct 10, 2011)

`sysctl -n hw.ncpu`


----------



## luo (Oct 11, 2011)

`sysctl hw.ncpu`?
I need a API or method in kernel space. Such as num_online_cpus(), which is a *Linux kernel API*.


----------



## DutchDaemon (Oct 11, 2011)

Have a browse in http://www.freebsd.org/doc/en_US.ISO8859-1/books/developers-handbook/ and look in /usr/src/sys/kern/ (and above).


----------



## SIFE (Oct 22, 2011)

```
#include <sys/param.h>
#include <sys/sysctl.h>

#include <stdio.h>


int main(int argc, char **argv) {
	int error, ncpu, req[2];
	size_t len;
	
	req[0] = CTL_HW;
	req[1] = HW_NCPU;
	
	len = sizeof(ncpu);
	error = sysctl(req, 2, &ncpu, &len, NULL, 0);
	if (error < 0)
		return;
	
	printf("Number of CPU's you have: %d\n", ncpu);
	
	return 0;
}
```
I hope this help, more information.


----------



## luo (Oct 26, 2011)

SIFE said:
			
		

> ```
> #include <sys/param.h>
> #include <sys/sysctl.h>
> 
> ...



thanks


----------



## saif (Apr 23, 2014)

I want it in kernel module. So I need a KPI to find number of online cpu> Also I need a per cpu variable?

Thanks


----------

