Rameez Rameez - 1 year ago 52
Perl Question

Logic to evenly distribute an array of time n number of arrays using perl

I need help to create a perl program to distribute array of execution time of program (in seconds) to n number of arrays.

Eg. I have an array which contains previous execution time of programs.


My aim is to reduce the total execution time by distributing these programs to multiple servers. For eg, if i have 5 servers with me, i need to distribute these programs to 5 servers such way that time to complete is execution of all program is lowest.

Output expected is something like this, this is just an example,


So that bigger programs are distributed to different servers.

Answer Source
use strict;
use warnings;
use v5.10;
use Data::Dumper;

my $servers_number = 5;
my @source = (20, 80, 340, 10, 90, 100, 40, 450, 60);
my @result;

@source = sort {$b <=> $a} @source;
my @server_times;

foreach my $time_chunk (@source)
    my $server_index = get_less_loaded_server_index();
    $result[$server_index] //= [ ];

    push @{$result[$server_index]}, $time_chunk;
    $server_times[$server_index] += $time_chunk;

sub get_less_loaded_server_index
    my $lessest_time;
    my $selected_server;

    for (my $i = 0; $i < $servers_number; $i++)
        $server_times[$i] //= 0;

        if (!defined $selected_server || $lessest_time > $server_times[$i])
            $lessest_time = $server_times[$i];
            $selected_server = $i;
    return $selected_server;

say Dumper(\@result);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download