Skip to content

Instantly share code, notes, and snippets.

@smls
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smls/a1f6033c142202bddc4d to your computer and use it in GitHub Desktop.
Save smls/a1f6033c142202bddc4d to your computer and use it in GitHub Desktop.

Perfect Shuffle performance

The code

Commented-out lines are alternatives to the preceding default line.

#!/usr/bin/env perl6

sub perfect-shuffle (@deck) {
    my $mid = @deck / 2;        # <default>
#   my $mid = +@deck div 2;     # intmath
#   my int $mid = +@deck div 2; # nativeintmath

    flat @deck[0 .. $mid-1] Z @deck[$mid .. *-1];              # <default>
#   (0..($mid - 1)).map({ @deck[$_, $_ + $mid] }).flat;        # map
#   (0..($mid - 1)).map({ @deck[$_], @deck[$_ + $mid] }).flat; # map_noslice
#   my @result = 0 xx +@deck;                                  # nativeloop
#   loop (my int $i = 0; $i < $mid; $i++) {                    # nativeloop
#       @result[$i*2] = @deck[$i];                             # nativeloop
#       @result[$i*2 + 1] = @deck[$i + $mid]                   # nativeloop
#   }                                                          # nativeloop
#   @result;                                                   # nativeloop
}

for 8, 24, 52, 100, 1020, 1024, 10000 -> $size {
    my @deck = ^$size;
    
    my $n;
    loop {
        $n++;
        @deck = perfect-shuffle @deck;   # <default>
#       @deck := perfect-shuffle @deck;  # bind
        last if [<] @deck;
    }
    
    printf "%5d cards: %4d\n", $size, $n;
}

"Benchmark" results

Run time is the "real time" as reported by the Unix time command, averaged from two runs per row, on Rakudo 2015.05-194-g9c8cb67 + MoarVM 2015.05-79-g458940f.

The profile runs were made separately.

zip implementation | variant | run time | profile -------------------|:---------------------|:---------:|---------:|:--------- Z (default) | | 810 sec | link map | | 1115 sec | map_noslice | | 80 sec | link map_noslice | bind | 104 sec | link nativeloop | | 59 sec | link nativeloop | intmath | 29 sec | link nativeloop | intmath + bind | 26 sec | link nativeloop | nativeintmath + bind | 19 sec | link

The Perl 5 version runs in a little over 1 sec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment