Getting the Cocoa (Mac OS X) Processor Count — How Many Processors (Processor Cores) Are Present?
©2006 Darel Rex Finley.  This complete article, unmodified, may be freely distributed for educational purposes.

This code (or something just like it) is found in multiple places on the web; I'm not the original author!

#import <sys/param.h >
#import <sys/sysctl.h>

int getProcessorCount() {

  int     count ;
  size_t  size=sizeof(count) ;

  if (sysctlbyname("hw.ncpu",&count,&size,NULL,0)) return 1;

  return count; }

That is "NULL", not "nil", by the way.

This function will return the number of processors (processor cores, actually), and if for some reason it can't get that number, it will return 1.

As far as I know, there's no reason to call this function more than once while your app is running.  I don't think the number of processor cores can change without a total system shutdown (and subsequent hardware modification!).

Note:  If you're using multithreading in your app, you'll probably need to know about NSLock.

Update:  I've been told that you can get the number of processors simply by calling MPProcessors().  It's a Carbon function, so whether it will be available to your compiler in the future is an open question.  But if it compiles now, your compiled app should be fine whether or not MPProcessors() gets axed someday.

Feel free to send me an e-mail about this page!  I'm no Cocoa expert, and could probably use any advice you'd care to throw my way.

Does the brace style in the above code sample freak you out?  Click here to see it explained in a new window.

Quicksort  |  Point in polygon  |  Mouseover menus  |  Gyroscope  |  Osmosis  |  Polarizer experiment  |  Gravity table equilibrium  |  Calculus without calculus  | Overlapping maze