2017-08-26 140 views
-1

我得到35秒執行此代碼。如何減少執行時間?我應該在這個源代碼中改變什麼。減少循環執行時間

$file_handle = fopen("WMLG2_2017_07_11.log", "r"); 
while (!feof($file_handle)) { 
    $line = fgets($file_handle); 
    if (strpos($line, '[email protected] [WMLG2] >') !== false) { 
     $namafileA = explode('> ', $line); 
     $namafile = str_replace(' ', '_', $namafileA[1]); 
     $filenameExtension = $namafile.".txt"; 
     $file = preg_replace('/[^A-Za-z0-9\-_.]/', '', $filenameExtension); // hapus special character kecuali "." dan "_" 
    } else { 
     $newfile = fopen("show_command_file_Tes2/$file", "a"); 
     fwrite($newfile, $line); 
    } 
} 
fclose($file_handle); 

回答

0

我發現了一些錯誤,你用原始代碼可能會影響你的性能,但我不知道有多少。

如果我理解正確,您打開一個日誌文件並將消息排序到單獨的文件。

您尚未從日誌文件中粘貼示例,但我假設您有重複的文件目標,並非日誌文件的每一行都有單獨的文件目標。

您的代碼打開,但從不關閉句柄,並且在腳本運行期間它保持打開狀態。文件句柄不在垃圾回收器的外部範圍上關閉,您必須手動執行以釋放資源。

基於此,您應該存儲文件指針(或至少關閉它們)並重新使用那些已經打開的句柄。在執行過程中至少打開X行句柄,並且不關閉/重新使用它,其中X是文件中的行數。

我注意到的其他事情,你的線可能是長的,這是一個罕見的情況下,PHP的strpos()函數可能比匹配字符串正確位置的正則表達式慢。如果沒有日誌文件,我不能肯定地說,因爲preg_match()是簡單/短字符串相當昂貴的功能(strpos()是方式更快。)

如果它的日誌文件,最有可能與「根@ CLA」開始...字符串,如果可以用^(字符串的初始值)或$(字符串的結尾)指定字符串位置,則應嘗試匹配該字符串。

<?php 

$file_handle = fopen("WMLG2_2017_07_11.log", "r"); 

//you 'll store your handles here 
$targetHandles = []; 

while (!feof($file_handle)) 
{ 
    $line = fgets($file_handle); 
    if (strpos($line, '[email protected] [WMLG2] >') !== false) 
    { 
     $namafileA = explode('> ', $line); 
     $namafile = str_replace(' ', '_', $namafileA[1]); 
     $filenameExtension = $namafile . ".txt"; 
     $file = preg_replace('/[^A-Za-z0-9\-_.]/', '', $filenameExtension); // hapus special character kecuali "." dan "_" 
    } 
    else 
    { 
     //no $file defined, most likely nothing to write yet 
     if (empty($file)) 
     { 
      continue; 
     } 

     //if its not open, we'll make them open 
     if (empty($targetHandles[$file])) 
     { 
      $targetHandles[$file] = fopen("show_command_file_Tes2/$file", "a"); 
     } 
     //writing the line to target 
     fwrite($targetHandles[$file], $line); 
    } 
} 

//you should close your handles every time 
foreach ($targetHandles as $handle) 
{ 
    fclose($handle); 
} 

fclose($file_handle); 
+0

從你的代碼中,變量$文件不確定的,如果你想看到它 這裏的日誌文件 https://www.dropbox.com/s/z8tvmegokghrjok/WMLG2_2017_07_11.log?dl=0 @Fiber –

+0

是的,你是對的,但我不知道你用這個變量的意圖是什麼,你正在定義'$ file = preg_replace('/ [^ A-Za-z0-9 \ -_。] /','',$ filenameExtension); // hapus特殊字符kecuali「。」 dan「_」')'但是這可能是未定義的。讓我編輯我的帖子並糾正它。 – Fiber

+0

$ file = preg_replace('/ [^ A-Za-z0-9 \ - 。] /','',$ filenameExtension)im使用它來刪除所有空間,因爲如果im沒有定義它,文件名將是 ex:show_alarm_active .txt 在最後一個字符串中存在空格,然後我放了擴展名 –