大型 Perl6 CArray 上的高性能数学运算



我有一些由本机子返回的大型 CArray,我需要对其执行基本的元素级数学运算。CArrays 通常在 10^6 个元素的数量级上。我发现对它们调用 .list 将它们视为正常的 Perl6 类型是非常昂贵的。有没有办法在保持它们 CArray 的同时对它们进行高性能的元素级操作?

简短的测试脚本来计时我尝试过的一些方法:

#!/usr/bin/env perl6
use v6.c;
use NativeCall;
use Terminal::Spinners;
my $list;
my $carray;
my $spinner = Spinner.new;
########## create data stuctures ##########
print "Creating 10e6 element List and CArray  ";
my $create = Promise.start: {
    $list = 42e0 xx 10e6;
    $carray = CArray[num32].new($list);
}
$spinner.await: $create;
########## time List subtractions ##########
my $time = now;
print "Substracting two 10e6 element Lists w/ hyper  ";
$spinner.await( Promise.start: {$list >>-<< $list} );
say "List hyper subtraction took: {now - $time} seconds";
$time = now;
print "Substracting two 10e6 element Lists w/ for loop  ";
my $diff = Promise.start: {
    for ^$list.elems {
        $list[$_] - $list[$_];
    }
}
$spinner.await: $diff;
say "List for loop subtraction took: {now - $time} seconds";
########## time CArray subtractions ##########
$time = now;
print "Substracting two 10e6 element CArrays w/ .list and hyper  ";
$spinner.await( Promise.start: {$carray.list >>-<< $carray.list} );
say "CArray .list and hyper subtraction took: {now - $time} seconds";
$time = now;
print "Substracting two 10e6 element CArrays w/ for loop  ";
$diff = Promise.start: {
    for ^$carray.elems {
        $carray[$_] - $carray[$_];
    }
}
$spinner.await: $diff;
say "CArray for loop subtraction took: {now - $time} seconds";

输出:

Creating 10e6 element List and CArray |
Substracting two 10e6 element Lists w/ hyper -
List hyper subtraction took: 26.1877042 seconds
Substracting two 10e6 element Lists w/ for loop -
List for loop subtraction took: 20.6394032 seconds
Substracting two 10e6 element CArrays w/ .list and hyper /
CArray .list and hyper subtraction took: 164.4888844 seconds
Substracting two 10e6 element CArrays w/ for loop |
CArray for loop subtraction took: 133.00560218 seconds

for 循环方法似乎最快,但 CArray 的处理时间仍然比 List 长 6 倍。

有什么想法吗?

只要您可以使用不同的本机数据类型,Matrix 和 Vector,您就可以使用 Fernando Santagata 的 Gnu 科学图书馆的(也是本机)端口。它有一个可以使用的Vector.sub函数。

#!/usr/bin/env perl6
use v6.c;
use NativeCall;
use Terminal::Spinners;
use Math::Libgsl::Vector;
my $list;
my $carray;
my $spinner = Spinner.new;
########## create data stuctures ##########
print "Creating 10e6 element List and CArray  ";
my $list1 = Math::Libgsl::Vector.new(size => 10e6.Int);
$list1.setall(42);
my $list2 = Math::Libgsl::Vector.new(size => 10e6.Int);
$list2.setall(33);
########## time List subtractions ##########
my $time = now;
print "Substracting two 10e6 element Lists w/ hyper  ";
$spinner.await( Promise.start: { $list1.sub( $list2)} );
say "GSL Vector subtraction took: {now - $time} seconds";

这需要:

GSL Vector subtraction took: 0.08243 seconds

这对你来说足够快吗? :-)

最新更新