Reedy
Member
Registered: 11th Apr 04
Location: Hammersmith
User status: Offline
|
I had to do a test for a job and they gave me this question.
Q2.
Develop an efficient algorithm for a weighted round robin scheme which evenly spreads
load between several servers, taking into account the “weight” of each server (more weight
means that server can handle more load).
$servers = array(
"127.0.0.1",
"127.0.0.2",
"127.0.0.3",
"127.0.0.4"
);
$weights = array(50, 25, 15, 10);
$picked = array();
$total = 100000;
for($i = 0; $i < $total; $i++) {
$server = weightedRoundRobin($servers, $weights);
$picked[$server]++;
}
for($i = 0; $i < count($servers); $i++) {
$server = $servers[$i];
$times = $picked[$server];
$percent = round(($times / $total) * 100, 2);
echo "{$server} picked {$times} times ({$percent}% of total)<br />";
}
function weightedRoundRobin($servers, $weights) {
// ... your algorithm. Return a server IP address.
}
At first I wasnt sure how to approach it but in the end I came up with this solution:
function weightedRoundRobin($servers, $weights)
{
for ( $i=0; $i<count( $weights ); $i++ )
{
for ( $j=0; $j< $weights[$i]; $j++ )
{
$randomArray[] = $i;
}
}
$location = $servers[$randomArray[array_rand($randomArray)]];
return $location;
}
Im just wondering if anybody else has a better solution.
|