#!/usr/bin/perl -w
use strict;
$|++;

my $ncpu=0;

if (( $^O eq "solaris" ) || ( $^O eq "dec_osf" )) {
	open(CPU,"/usr/sbin/psrinfo |") || die "Can't run psrinfo:$!";
	while (<CPU>) { $ncpu += 1; }
	close(CPU);
	print "$ncpu\n";
}
elsif ( $^O eq "linux" ) {
	open(CPU,"</proc/cpuinfo") || die "Can't read /proc/cpuinfo:$!";
	$ncpu = scalar grep(/^processor\s+:/,<CPU>);
	close(CPU);
	if ( $ncpu == 0 ) { # is this Linux on Alpha?
		open(CPU,"</proc/cpuinfo") || die "Can't read /proc/cpuinfo:$!";
		my ($cpuline) = grep(/^cpus detected\s+: /,<CPU>);
		close(CPU);
		if ( $cpuline ) {
			($cpuline, $ncpu) = split /: /, $cpuline;
			chomp $ncpu;
		}
	}
	print "$ncpu\n";
}
elsif (( $^O eq "darwin" ) || ( $^O eq "openbsd" )) {
	open(CPU,"/usr/sbin/sysctl -n hw.ncpu|") || die "Can't read sysctl:$!";
	print <CPU>;
	close(CPU);
}
elsif (( $^O eq "freebsd" ) || ( $^O eq "netbsd" )) {
	open(CPU,"/sbin/sysctl -n hw.ncpu|") || die "Can't read sysctl:$!";
	print <CPU>;
	close(CPU);
}
elsif ( $^O eq "irix" ) {
	open(CPU,"/usr/sbin/mpadmin -n |") || die "Can't run mpadmin:$!";
	while (<CPU>) { $ncpu += 1; }
	close(CPU);
	print "$ncpu\n";
}
elsif ( $^O eq "hpux" ) {
	open(CPU,"/usr/bin/mpsched -s |") || die "Can't run mpsched:$!";
	my ($cpuline) = grep(/^Processor Count\s+: /,<CPU>);
	close(CPU);
	($cpuline, $ncpu) = split /: /, $cpuline;
	print $ncpu;
}
else {
	warn "Unknown platform, just saying 1 CPU!\n";
	print "1\n";
}
