My Tutorials/C Programming Tutorial/Cpucount.c

From ThorstensHome
Revision as of 13:04, 26 July 2008 by WikiSysop (Talk)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This program tests how many CPUs you have.

using the cpufreq package


 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.


#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);
    cout << "your compi has " << cpucount << " cpus" << endl;
  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