所以,我正在考虑使用分叉或线程来做一些简单的并行化。为了确保这样做是值得的,我编写了三个简单的脚本来对顺序、线程和分叉进行基准测试。我使用了两种非常简单的方法来初始化数组数组,然后使用另一种方法来查找每个数组中的最大元素并将其写入文件。
方法:
sub initialize
{
for (my $i=0; $i <= 2; $i++)
{
for (my $j=0; $j < 5000000; $j++)
{
$array[$i][$j]=$j+$i;
}
}
}
sub getMax
{
my $num = shift;
my $array = shift;
my $length=scalar(@{$array});
my $max=-9**9**9;
my @ra;
for (my $i=0; $i < $length; $i++)
{
if ($max < ${$array}[$i])
{
$max=${$array}[$i];
}
}
tie @ra, 'Tie::File', "test.txt" or die;
$ra[$num]=$max;
}
顺序:
my $start = Time::HiRes::time();
for (my $count = 0; $count <= 2; $count++)
{
getMax($count,$array[$count]);
}
my $stop = Time::HiRes::time();
my $duration = $stop-$start;
print "Time spent: $duration\n";
print "End of main program\n";
穿线:
my @threads=();
my $start = Time::HiRes::time();
for (my $count = 0; $count <= 2; $count++)
{
my $t = threads->new(\&getMax, $count, $array[$count]);
push(@threads,$t);
}
foreach (@threads)
{
my $num = $_->join;
}
my $stop = Time::HiRes::time();
my $duration = $stop-$start;
print "Time spent: $duration\n";
print "End of main program\n";
分叉:
my $pm = Parallel::ForkManager->new(3);
my $start = Time::HiRes::time();
for (my $count = 0; $count <= 2; $count++)
{
my $pid = $pm->start and next;
getMax($count,$array[$count]);
$pm->finish;
}
$pm->wait_all_children;
my $stop = Time::HiRes::time();
my $duration = $stop-$start;
print "Time spent: $duration\n";
print "\nEnd of main program\n";
连续:2.88 秒
穿线:4.10 秒
分叉:3.88 秒
我想出于我的目的(显然不是这个,但计算量不是太大),线程/分叉没有帮助。我知道这两者不仅仅用于时间效率,但我想这是取决于你在做什么的好处之一。所以,我的问题是线程/分叉究竟什么时候真正使一个人的代码运行得更快?