15

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();
1
  • 5
    As an aside: (1) Always use strict; use warnings;. The warnings module is superior to the -w switch. (2) Use a Thread::Queue instead of protecting an array with a semaphore. (3) You can't declare a sub like sub &foo { ... }. It is sub foo { ... }. (4) The $fname can be undef. You don't account for this when printing it out and executing the csh.
    – amon
    Aug 21, 2013 at 14:41

7 Answers 7

15

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;
7

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;
0
4

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

2

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

my $numberofcores = $ENV{"NUMBER_OF_PROCESSORS"};
0

This is a tight version I am using:

use Path::Tiny;
sub getProcessors {
    my @cpuinfo = split "\n", path("/proc/cpuinfo")->slurp_utf8();
    return scalar (map /^processor/, @cpuinfo) ;
}
0

It seems $ENV{NUMBER_OF_PROCESSORS} works nicely for Windows, but I was looking for a Perl one-liner which works on Linux and Cygwin too, which does not call external executables. Unfortunately I do not have Sys::* packages and I cannot install them.

I started with getconf(1). It has shows to condfiguration variables: _NPROCESSORS_CONF and _NPROCESSORS_ONLN. Using strace(1) on getconf(1) (strace -o s.log getconf -a) it turned out that these information is grubbed using /sys/devices/system/cpu path. This dir has cpu[0-9]+ like sub-dirs, which makes the life a bit complicated. So I returned to the well known /proc/cpuinfo and this is the one-liner:

my $cpus = do { local @ARGV='/proc/cpuinfo'; grep /^processor\s+:/, <>;};

Maybe this could be extended to get the number of online cores, but it is sufficient for now.

0

Old thread but I recently wrote this and it seems to work well...

sub getCoreCount {
  my $cpucount = 0;
  open(my $CPUINFO, "<", "/proc/cpuinfo") or die $!;


  while (my $line = <$CPUINFO>) {
    if ($line =~ /^processor/) {
      $cpucount++;
    }
  }

  close $CPUINFO;
  return $cpucount;
}

print "CPUs: ".getCoreCount()."\n";

for OS X/macOS I have this https://gist.github.com/ablakely/4328790d106ae448885fe8949f5f4301

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.