簡體   English   中英

如何提高我的讀取文件功能和獲取數據的性能,而不是file()?

[英]How to improve my reading a file function and grabbing the data for better performance than file()?

我的文件每天00:00都在重新創建,並且一天之中開始緩慢地添加一行一行作為日志文件。 該文件大約1 mb,一天結束時大約有6,000行。 因此,這不是一個很小的文件。 我的問題是,如何使腳本具有更好的性能,因為file()實際上是逐行讀取整個文件,那么有什么更好的方法呢? 該文件為.txt格式的純文本格式,以下是該文件的示例行:

1,42,16, 201,stackoverflow_user, 1, 6762160, 39799, 9817242, 6762160, 39884, 10010545,stackoverflow_user, 2, 1351147, 1165, 483259, 1351147, 1115, 241630, 0 
1,46,27, 201,[stackoverflow_user | stackoverflow_userother], 1, 4078465, 286991, 1594830, 4078465, 287036, 1643156,stackoverflow_user, 2, 1357147, 1115, 241630, 1357147, 1065, 120815, 0

我的功能:

# read a file into an array
$lines = file('C:/path/to/file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

# flip our array over so the last lines of the file are first.
$lines = array_reverse($lines);
$n = 1;
$wanted = 21; # or however many lines you want.
$content = '';

foreach ($lines as $l) {
   # treat the data as comma-separated values
   $arr = explode(",", $l);
   # if col 5 has multiple values, take the first one
   if (preg_match("/\[(.+?) \|/", $arr[4], $matches)) {
       $arr[4] = $matches[1];
   }
   # is arr[4] the same as arr[12]?
   if ($arr[4] !== $arr[12]) {
       # these two are not equal, so use these values
       $data = array('rank-pos' => $n++, 'rank-name' => $arr[4], 'rank-dmuser' => $arr[12]);
       $content .= Template::Load('rankinguserdm-' . ($n % 2 == 1 ? 2 : 1), $data);
   }
   # have we got enough data?
   if ($n === $wanted) {
       break;
   }
}

        $this->content = Template::Load('user_rankingsdm', array('rankings' => $content));
    }

我對問題的代碼進行了微調以提高性能。 在我的服務器上,反轉陣列大約需要0.7ms,而循環大約需要0.2ms。 所以$lines = array_reverse($lines); 放在下面的解決方案中。

<?php
for ($i=0; $i<1000;$i++) {
    $lines[] = '1,42,16, 201,stackoverflow_user, 1, 6762160, 39799, 9817242, 6762160, 39884, 10010545,stackoverflow_user, 2, 1351147, 1165, 483259, 1351147, 1115, 241630, 0';
    $lines[] = '1,46,27, 201,[stackoverflow_user | stackoverflow_userother], 1, 4078465, 286991, 1594830, 4078465, 287036, 1643156,stackoverflow_user, 2, 1357147, 1115, 241630, 1357147, 1065, 120815, 0';
}
$lines_count = count($lines) - 1;
$content = [];
for ($i=$lines_count; $i > $lines_count - 21; $i--) {
   $l = $lines[$i];
   $content[] = $l;
}
print_r($content);

工作示例: https//eval.in/207364

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM