Cpucount.c
From ThorstensHome
Home < Tutorials < C Programming Tutorial < Cpucount.cThis program tests how many CPUs you have.
using the cpufreq package
main.cpp
/*
This tests how many CPUs you have.
(c) 2007 by Thorsten Staerk
*/
#include <cpufreq.h>
#include <stdio.h>
int main ()
{
int i=0;
while (!cpufreq_cpu_exists(++i));
printf("Your computer has %i CPUS online\n",i);
}
Compile, link and run
With SUSE Linux, I had to install an rpm package named cpufrequtils. Then you can build and run it like this:
g++ -lcpufreq -o cpucount main.cpp && ./cpucount
using glibc-devel
This program is also discussed under syscall.cpp because you can use it to make processes run on specific processors.
main.cpp
#include <sched.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main (int argc, char* argv[])
{
int cpucount=0;
int pid=atoi(argv[1]);
cpu_set_t mask;
unsigned int len = sizeof(mask);
// get cpu count
sched_getaffinity(pid, len, &mask);
cpucount=CPU_COUNT(&mask);
cout << "your compi has " << cpucount << " cpus" << endl;
CPU_ZERO(&mask);
CPU_SET(0,&mask);
cout << "cpu settings: ";
for (int i=cpucount-1; i>=0; --i) cout << CPU_ISSET(i,&mask);
cout << endl;
sched_setaffinity(pid, len, &mask);
}
Compile, link and run
g++ -o cpucount main.cpp && ./cpucount

