首页 > 解决方案 > perl排序函数效率

问题描述

我将大约 40,000 个字符串,每个大约 50 个字符导入到一个数组中,然后我需要对其进行排序。最初我打算进行合并排序,但后来我意识到 perl 中有一个内置的排序功能。内置排序功能的效率如何?我可以从中获得什么运行时间?如果您认为这可能会超过几分钟,我将采用合并排序方式,并感谢您提供的任何好的示例。

标签: sortingperl

解决方案


您不太可能编写出比 Perl 的内置排序更快的排序,后者在过去几十年中已经优化。

无法说出您可能期望什么样的运行时,因为我们对您的机器一无所知,但您可以自己尝试内置排序,看看它是如何运行的,然后再担心它会更快。过早的优化是万恶之源。

这是我整理的一个测试程序。在我的 Macbook 上,排序 500,000 个字符串需要 0.47 秒(您排序的 10 倍)。

$ cat foo.pl
#!/usr/bin/perl

use warnings;
use strict;
use 5.010;

use Time::HiRes qw( gettimeofday tv_interval );

my $nrecs = 500_000;

my @strings = map { random_string() } 1 .. $nrecs;

my $t0 = [gettimeofday];
my @sorted = sort @strings;

my $elapsed = tv_interval( $t0 );

say "Took $elapsed to sort $nrecs strings";

sub random_string {
    my @chars = ( 'a'..'z', 'A'..'Z' );
    return join( '', map { $chars[rand @chars] } 1..10 );
}

$ perl foo.pl
Took 0.474914 to sort 500000 strings

推荐阅读