一个有趣的问题,对于 Uni 课程的一部分,我们面临着运行模拟服务器接收请求然后处理它们的挑战。我已经多次构建和重建了它,我认为它已经尽可能高效了,你有什么可以提高这个程序的效率的吗?
模拟运行,$simulationLength
并且每次$currentTime
都有1/$arrival_rate
新请求到达的机会。一个大小的队列$maxQueueSize
保存这些请求,如果队列已满,则拒绝它们。对于每个$currentTime
CPU 可能会从队列中移除一个项目$queue
并在其上工作$executionTime
几秒钟,此时 CPU(服务器)从繁忙队列中移除并且可以自由地处理另一个请求。
我的代码:
<?php
...SNIP error checking...
$queue_size = isset($argv[1]) ? $argv[1] : 10000;
$arrival_rate = isset($argv[2]) ? $argv[2] : 3;
$number_of_servers = isset($argv[3]) ? $argv[3] : 2;
$execution_time = isset($argv[4]) ? $argv[4] : 25;
...SNIP error checking...
$simulationLength = 1000000;
$arrivalRate = $arrival_rate;
$executionTime = $execution_time;
$busyServers = array();
$freeServers = $number_of_servers;
$currentTime = 0;
$currentQueueSize = 0;
$maxQueueSize = $queue_size; //Max
$queue = array();
//Stats
$totalRequests = 0;
$rejectedRequests = 0;
$queueSize = array_fill(0, 100, $simulationLength);
$totalWaitingTime = 0;
//while the simulation is running
while($currentTime++ < $simulationLength) {
//a request has arrived
if(mt_rand(1, $arrival_rate)==1) {
$totalRequests++;
//Adding to the queue
if($currentQueueSize < $maxQueueSize) {
$currentQueueSize++;
array_push($queue, $currentTime); //add to the end of the queue
} else {
$rejectedRequests++;
}
} //end request arrived
//Only one server can fetch requests at a time
if(!empty($busyServers)&&reset($busyServers) < $currentTime) {
unset($busyServers[key($busyServers)]); //remove first element - efficient
$freeServers++; //increase free servers
}
//Only one server can fetch requests at a time
if($currentQueueSize>0&&$freeServers>1) {
$currentQueueSize--;
reset($queue); //reset pointer
$queueTime = $queue[key($queue)]; //read of the front
unset($busyServers[key($busyServers)]); //delete off print
$freeServers--; //use up a server
$busyServers[] = $currentTime + $executionTime; //mark when free
$totalWaitingTime += ($currentTime - $queueTime) + $executionTime;
}
$queueSize[$currentTime] = $currentQueueSize;
}
printf("Requests served %d\n", $totalRequests);
printf("Rejected requests %d\n", $rejectedRequests);
printf("Total waiting time %d\n", $totalWaitingTime);
printf("Percentage of rejected requests %0.1f\n", $rejectedRequests/$totalRequests);
printf("The average queue size %d\n", array_sum($queueSize)/sizeof($queueSize));
printf("Average response time %d\n", $totalWaitingTime/$totalRequests);
?>
谢谢你的时间,