babno
babno

Reputation: 309

perl sort function efficiency

I'm importing roughly 40,000 strings each roughly 50 characters into an array which I then need to sort. Initially I was going to make a merge sort, but then I realized there is a built in sort function into perl. How is the efficiency on the built in sort function and what runtime might I expect from it? If you think it'd likely be more than a few minutes I'll go the merge sort way, and would appreciate any good examples you could provide.

Upvotes: 1

Views: 146

Answers (2)

Andy Lester
Andy Lester

Reputation: 93676

It is unlikely that you're going to be able to write a sort that's faster than Perl's built-in sort that has been optimized for the past few decades.

It's impossible to say what kind of runtime you might expect, since we don't know anything about your machine, but try the built-in sort yourself and see how it runs before you worry about doing it faster. Premature optimization is the root of all evil.

Here's a test program I put together. It takes 0.47 seconds on my Macbook to sort 500,000 strings (10x what you're sorting).

$ 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

Upvotes: 6

choroba
choroba

Reputation: 241898

The following takes less than half a second on my laptop, even with generating and printing all the strings.

#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my @array = map {
    join "", map chr(32 + rand 95), 1 .. 50
} 1 .. 40_000;

my @sorted = sort @array;
say for @sorted;

So, don't worry about the performance and don't bother implementing the sort yourself.

Upvotes: 5

Related Questions