我正在尝试同时学习Perl 6和并行/并发。
对于一个简单的学习练习,我有一个550'.htm'文件的文件夹,我想要所有这些文件中的代码行总和。到目前为止,我有这个:
use v6;
my $start_time = now;
my $exception;
my $total_lines = 0;
my @files = "c:/testdir".IO.dir(test => / '.' htm $/);
for @files -> $file {
$total_lines += $file.lines.elems;
CATCH {
default { $exception = $_; } #some of the files error out for malformed utf-8
}
}
say $total_lines;
say now - $start_time;
在大约3秒内得到577,449的总和。
我如何重写它以利用Perl 6并行思想?我意识到节省的时间不会太多,但它可以作为概念的证明。
答案 0 :(得分:1)
实施Christoph的建议。计数略高于我原来的帖子,因为我现在能够使用encode latin1读取格式错误的UTF-8文件。
use v6;
my $start_time = now;
my @files = "c:/iforms/live".IO.dir(test => / '.' htm $/);
my $total_lines = [+] @files.race.map(*.lines(:enc<latin1>).elems);
say $total_lines;
say now - $start_time;
答案 1 :(得分:-1)
use v6;
my $start_time = now;
my $exception;
my @lines;
my $total_lines = 0;
my @files = "c:/testdir".IO.dir(test => / '.' htm $/);
await do for @files -> $file {
start {
@lines.push( $file.lines.elems );
CATCH {
default { $exception = $_; } #some of the files error out for malformed utf-8
}
}
}
$total_lines = [+] @lines;
say $total_lines;
say now - $start_time;