Perl中的CPU /内核数

问题描述 投票:13回答:6

如何获取Perl中的CPU或内核数量。我想要这个,决定动态创建线程数。下面我创建了3个主题。但我想根据该机器中的核心数创建线程。

#!/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();
perl
6个回答
14
投票

查看CPAN模块,例如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;

6
投票

老问题,但这里是我如何告诉我的Linux服务器上的CPU数量:

#!/usr/bin/perl
chomp(my $cpu_count = `grep -c -P '^processor\\s+:' /proc/cpuinfo`);
print("CPUs: $cpu_count\n");

这仅适用于linux / cygwin。从好的方面来说,这个解决方案不需要安装任何额外的perl模块。

编辑: Barak Dagan建议使用“perl only”解决方案(我还没有测试过):

open my $handle, "/proc/cpuinfo" or die "Can't open cpuinfo: $!\n";
printf "CPUs: %d\n", scalar (map /^processor/, <$handle>) ; 
close $handle;

3
投票

getNumCpusSys::CpuAffinity方法适用于许多不同的操作系统和配置。


2
投票

对于无法使用Sys :: Info或Sys :: CpuAffinity的基于Windows的用户的替代方法:

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

0
投票

这是我正在使用的紧凑版本:

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

0
投票

似乎$ ENV {NUMBER_OF_PROCESSORS}适用于Windows,但我正在寻找一个可在Linux和Cygwin上运行的Perl单行程序,它不会调用外部可执行文件。不幸的是我没有Sys :: *包,我无法安装它们。

我从getconf(1)开始。它显示了condfiguration变量:_NPROCESSORS_CONF_NPROCESSORS_ONLN。在getconf(1)(strace(1))上使用strace -o s.log getconf -a,结果发现这些信息是使用/sys/devices/system/cpu路径生成的。这个目录有cpu[0-9]+像sub-dirs,这使生活有点复杂。所以我回到了着名的/proc/cpuinfo,这是单线:

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

也许这可以扩展到获得在线核心的数量,但现在已经足够了。

© www.soinside.com 2019 - 2024. All rights reserved.