時計を壊せ

駆け出しWebプログラマーの雑記

Perlの標準モジュールだけで比較的速いsleep_sort書いた

むっちゃ適当。

use strict;
use warnings;
use Data::Dumper;
use Time::HiRes qw/gettimeofday/;

sub timer(&$){
    my($code, $wait_time) = @_;

    return sub{
        my $start_time = shift;
        my $now_time   = shift;

        if(($now_time - $start_time) >= $wait_time){
            $code->();
            return 1;
        }else{
            return 0;
        }
    }
}

my $precision = 200;
sub timer_run{
    my @event    = @_;
    my $all      = scalar(@event);
    my $count    = 0;
    my @endflang = (0) x $all;

    my $start = (gettimeofday)[1] / $precision;
    while($count < $all){
        foreach my $i (0 .. ($all -1)){
            unless($endflang[$i]){
                my $stc = $event[$i]->($start, (gettimeofday)[1] / $precision);
                $count += $endflang[$i] = $stc;
            }
        }
    }
}

sub sleep_sort{
    my(@args) = @_;

    my @out;

    my @event;
    foreach my $i (@args){
        push( @event, timer{
            push(@out, $i);
        } $i);
    }
    timer_run(@event);

    return @out;
}

my @args = @ARGV or die "Usage: $0 3 5 6 7 2 1 55 6";

print "before...\n";
print Dumper(\@args);

my @sorted = sleep_sort(@args);

print "after...\n";
print Dumper(\@sorted);

無駄に、もはや何も使わないバージョンも作ったけど結構どうでもいい。
https://gist.github.com/980941