How to get number of CPU or Cores in Perl. I want this, to decide, creating number of threads dynamically. Below I have created 3 threads. But I want to create threads based on number of cores in that machine.
#!/usr/bin/perl -w
use threads;
use Thread::Semaphore;
my $semaphore = Thread::Semaphore->new();`enter code here`
my $cur_dir = "D:\\qout";
opendir( CURDIR, "$cur_dir" );
my @file_list : shared = readdir(CURDIR);
closedir(CURDIR);
$thr1 = threads->create( \&changemode, \@file_list, "th1" );
$thr2 = threads->create( \&changemode, \@file_list, "th2" );
$thr3 = threads->create( \&changemode, \@file_list, "th3" );
sub &changemode {
my ($file_list) = shift;
my ($message) = shift;
my ($i) = shift;
while (@{$file_list}) {
my $fname;
$semaphore->down();
if (@{$file_list}) {
$fname = shift(@{$file_list});
}
$semaphore->up();
print("$message got access of $fname\n");
system ("csh -fc \"chmod +w $fname\"");
#sleep (2);
}
}
$thr1->join();
$thr2->join();
$thr3->join();
Check out the CPAN modules such as Sys::Info::Device::CPU
use Sys::Info;
use Sys::Info::Constants qw( :device_cpu );
my $info = Sys::Info->new;
my $cpu = $info->device( CPU => %options );
printf "CPU: %s\n", scalar($cpu->identify) || 'N/A';
printf "CPU speed is %s MHz\n", $cpu->speed || 'N/A';
printf "There are %d CPUs\n" , $cpu->count || 1;
printf "CPU load: %s\n" , $cpu->load || 0;
Old question but here is how I tell the number of CPUs on my linux server:
#!/usr/bin/perl
chomp(my $cpu_count = `grep -c -P '^processor\\s+:' /proc/cpuinfo`);
print("CPUs: $cpu_count\n");
This only works in linux/cygwin. On the bright side this solution doesn't need any extra perl modules installed.
Edit:
Barak Dagan suggested a "perl only" solution (I haven't tested it):
open my $handle, "/proc/cpuinfo" or die "Can't open cpuinfo: $!\n";
printf "CPUs: %d\n", scalar (map /^processor/, <$handle>) ;
close $handle;
The getNumCpus
method of Sys::CpuAffinity
works on many different operating systems and configurations.
An alternative for windows-based users who cannot use Sys::Info or Sys::CpuAffinity:
my $numberofcores = $ENV{"NUMBER_OF_PROCESSORS"};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With