Difference between revisions of "My Tutorials/C Programming Tutorial/Cpucount.c"

From ThorstensHome
Redirect page
Jump to: navigation, search
m (1 revision(s))
 
(2 intermediate revisions by one user not shown)
Line 1: Line 1:
This program tests how many CPUs you have.
+
#REDIRECT [[Tutorials/C Programming Tutorial/Cpucount.c]]
 
+
= using the cpufreq package =
+
'''main.cpp'''
+
<pre>
+
/*
+
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);
+
}
+
</pre>
+
'''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'''
+
<pre>
+
#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);
+
}
+
</pre>
+
'''Compile, link and run'''
+
g++ -o cpucount main.cpp && ./cpucount
+

Latest revision as of 17:47, 29 June 2009