2012-11-24 53 views
0

我試圖做一個函數,它能夠通過一個給定的次數旋轉數組,然後返回第一個索引。但我所擁有的真的很慢很笨重。看看:陣列的低效旋轉

<?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

有沒有更好的方法來找出誰是索引0後x的旋轉量?

+2

這一翻譯轉了N次,爲什麼不乾脆返回第N指數? –

+0

你能舉個例子嗎?我不太清楚你的意思。 – dadord

回答

0

你的陣列轉動不慢,但它可以改善..我相信這是你的輪換代碼

您的代碼

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

return $startList[0]; 

可以消除環路與國防部進行更換。 。您仍然可以得到相同結果的方式是解決方案:

解決方案

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

你會得到同樣的結果。

簡單的基準測試&

$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)    | 
+1

這似乎有伎倆!我知道有這種東西的一些神奇的數學東西,謝謝讓我變得更聰明:-) – dadord

+0

歡迎:) – Baba