in reply to Multiprocessor (SMP) system detection

A reasonably portable way to do this is using the sysconf(3C) function. Unfortunately you can only call it from C.

If you use the amazing Inline module, a function to get the number of CPUs is as easy as

use Inline C => qq{
#include <unistd.h>
long nprocs() { return sysconf(_SC_NPROCESSORS_CONF); }
};

my $num_cpus = nprocs();

This get the number of CPUs configured; replace "CONF" with "ONLN" to get the number of CPUs on line.

UPDATE

The standard module POSIX defines POSIX::sysconf. Unfortunately it doesn't appear to define the constants _SC_NPROCESSORS_CONF and _SC_NPROCESSORS_ONLN, so it doesn't solve your problem.
  • Comment on Re: Multiprocessor (SMP) system detection

Replies are listed 'Best First'.
Re: Re: Multiprocessor (SMP) system detection
by clintp (Curate) on Jun 25, 2001 at 18:06 UTC
    Depending on his situation, it might be easier to build a table of known values for the constants and then just call sysconf anyway. As in:
    # Untested, but the constants are right use POSIX qw(sysconf); $const{linux}->{_SC_NPROCESSORS_CONF} = 83; $const{aix}->{_SC_NPROCESSORS_CONF} = 71; print sysconf($const{$^O}->{_SC_NPROCESSORS_CONF});
    If he's got more control over the target environment, he can use an h2ph-ish kind of tool to get them.
Re: Re: Multiprocessor (SMP) system detection
by sierrathedog04 (Hermit) on Jun 25, 2001 at 18:39 UTC
    This comment is actually more of a question.

    It seems to me that even though ANSI C may be widely available, any solution that involves calling a C function is inherently non-portable.

    I say that because in order to call a C function one would need to compile a call to the function. And even if ANSI C were widely available the mechanics of compiling C would differ. So no portable Makefile.PL could be created. Hence, non-portability.

      Well, if no portable Makefile.PL could be generated, Perl wouldn't be half as popular as it's today. Lots of modules on CPAN use C, including very popular ones like DBD::* and Date::Calc. All with a portable Makefile.PL That's what XS and the ExtUtils are for! And nowadays, the Inline family even gives us easy access to XS.

      -- Abigail

      Actually, the Inline module makes it possible to have C code that is compiled without changing your Makefile.PL on a number of systems. Now, whether the C code itself is portable depends on what it calls (for instance, there is no portable way to determine the number of processors). But it can be possible to make portable C routines that compile across platforms. Here's an example from the Inline::C::Cookbook :

      use Inline C => <<'END_C'; void greet() { printf("Hello, world\n"); } END_C greet;