阵列旋转效率低

时间:2012-11-24 08:49:55

标签: php arrays

我正在尝试创建一个能够在给定时间内旋转数组然后返回第一个索引的函数。但我所拥有的是非常缓慢和笨重的。看看:

<?php

/**
 * Get the current userid
 * @return integer
 */
public function getCurrentUser( DateTime $startDate, DateInterval $interval, DateTime $endDate, $currentUser, $users, $rotating )
{

    if ($rotating == 0)
    {
        return $currentUser;
    }

    $usrArray = array();
    $dateRange = new DatePeriod( $startDate, $interval, $endDate);

    // Push userIds to an array
    foreach ($users as $user)
    {
        $usrArray[] = $user->id;
    }

    // Get the number of iterations from startDate to endDate
    $steps = iterator_count($dateRange);

    // Find the initial position of the orignal user
    $key = array_search($currentUser, $usrArray);

    // Set up the array so index 0 == currentUser
    $usr = $usrArray;
    array_splice($usr, $key);
    $slice = array_slice($usrArray, $key);
    $startList = array_merge($slice, $usr);

    // Start rotating the array
    for ($i=0; $i < $steps; $i++)
    {
        array_push($startList, array_shift($startList));
    }

    return $startList[0];
}

这是PHP脚本超时前的Xdebug配置文件。 xdebug profile

在x旋转量之后,有没有更好的方法来确定谁是指数0?

1 个答案:

答案 0 :(得分:0)

您的阵列旋转速度不是很慢但可以改进..我相信这是您的旋转代码

您的代码

// Start rotating the array
for ($i=0; $i < $steps; $i++)
{
    array_push($startList, array_shift($startList));
}

return $startList[0];

你可以删除循环用mod替换它。你仍然可以得到相同结果的方法是解决方案:

<强>解决方案

return $startList[ $steps % count($startList)];

你会得到相同的结果。

简单的基准&amp;测试

$steps = 10000; <----------------- 10,000 steps 

set_time_limit(0);
echo "<pre>";
$file = "log.txt";
// Using your current code
function m1($steps) {
    $startList = range("A", "H");
    for($i = 0; $i < $steps; $i ++) {
        array_push($startList, array_shift($startList));
    }
    return $startList[0];
}

// Using InfiniteIterator
function m2($steps) {
    $startList = range("A", "H");
    $n = 0;
    foreach ( new InfiniteIterator(new ArrayIterator($startList)) as $l ) {
        if ($n == $steps) {
            return $l;
            break;
        }
        $n ++;
    }
}

// Simple MOD solution
function m3($steps) {
    $startList = range("A", "H");
    return $startList[ $steps % count($startList)];
}

$result = array('m1' => 0,'m2' => 0,'m3' => 0);

for($i = 0; $i < 1; ++ $i) {
    foreach ( array_keys($result) as $key ) {
        $alpha = microtime(true);
        $key($file);
        $result[$key] += microtime(true) - $alpha;
    }
}

echo '<pre>';
echo "Single Run\n";
print_r($result);
var_dump(m1($steps),m2($steps),m2($steps));
echo '</pre>';

输出

Single Run
Array
(
    [m1] => 0.00012588500976562
    [m2] => 0.00021791458129883
    [m3] => 7.7962875366211E-5   <----------------- Mod solution fastest 
)
string 'A' (length=1)               |
string 'A' (length=1)               |+------------- They all return same result
string 'A' (length=1)               |