|Title:||Portably Determining the Number of Processors in the System|
|Version:||$Revision: 1.2 $|
|Author:||Andreas Kupries <andreask at activestate dot com>|
|Created:||Monday, 13 September 2010|
A C API and Tcl command are proposed which return the number of CPUs (a.k.a. Processors a.k.a. Cores) in the system, portably wrapping the OS specific APIs for doing so.
With the relentless advance of multi-core chips it becomes sensible, IMVHO, to have a portable method of determining the number of CPUs (also called Processors or Cores) in the system.
This information is mostly important for the initialization of thread pools, in order to have a sensible number of worker threads which provide the maximum speedup without overloading the system. The general use-case the previous is an example of is the dynamic reconfiguration of an application or library to automatically adapt it to the resources available in the environment it finds itself in. That is, this is useful for multi-process applications as well.
Semi-concrete examples: The CRIMP package is currently single-threaded. For the best parallelization by threading, it should be possible to query the number of processors the application can use. A web server like Wub can make use of this functionality as well. They should not have to implement this on their own, duplicating the functionality, or, worse, each having slightly different implementations.
int Tcl_GetNumberOfProcessors(int flags)
Returns the number of processors for the current system, as provided by the OS. If the system is unable to provide this information the returned value is '1', as at least one processors is necessary to run anything at all.
The flags argument is not used. It is provided as a means of extensibility. Something which can be used in the future to distinguish between physical processors, hyperthreaded virtual processors, cores on a chip, number of processor chips, and the like. Right now such advanced queries are out of the scope of the TIP.
The main point of having the 'flags' argument now is that future extensions using it will not have to change the signature of the function.
Returns the number of processors for the current system, as provided by Tcl_GetNumberProcessors(0).
A reference implementation is provided at SourceForge .
The stackoverflow messaging board has a question on the various OS-specific APIs. See  for details.
This document has been placed in the public domain.
[Index] [History] [HTML Format] [Source Format] [LaTeX Format] [Text Format] [XML Format] [*roff Format (experimental)] [RTF Format (experimental)]TIP AutoGenerator - written by Donal K. Fellows