Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of CPU/Cores in Perl

Tags:

perl

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();
like image 433
user2704024 Avatar asked Aug 21 '13 14:08

user2704024


4 Answers

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;
like image 50
Brian Agnew Avatar answered Sep 23 '22 12:09

Brian Agnew


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;
like image 45
oᴉɹǝɥɔ Avatar answered Sep 22 '22 12:09

oᴉɹǝɥɔ


The getNumCpus method of Sys::CpuAffinity works on many different operating systems and configurations.

like image 22
mob Avatar answered Sep 21 '22 12:09

mob


An alternative for windows-based users who cannot use Sys::Info or Sys::CpuAffinity:

my $numberofcores = $ENV{"NUMBER_OF_PROCESSORS"};
like image 24
jing Avatar answered Sep 22 '22 12:09

jing