Home  >  Article  >  Backend Development  >  php超快高效率统计大文件行数_php技巧

php超快高效率统计大文件行数_php技巧

WBOY
WBOYOriginal
2016-05-16 20:11:45937browse

用php获取文件行数,网上给出的答案通常是使用file这样一次性读取,这样不适用在大文件。通常大文件大家用while来循环的逐行统计,这样的效率太慢

最快的方法是多行统计,每次读取N个字节,然后再统计行数,这样比逐行效率高多了。

测试情况,文件大小 3.14 GB

第1次:line: 13214810 , time:56.2779 s;
第2次:line: 13214810 , time:49.6678 s;

/*
 * 高效率计算文件行数
 * @author axiang
*/
function count_line($file){
  $fp=fopen($file, "r");
  $i=0;
  while(!feof($fp)) {
    //每次读取2M
    if($data=fread($fp,1024*1024*2)){
      //计算读取到的行数
      $num=substr_count($data,"\n");
      $i+=$num;
    }
  }
  fclose($fp);
  return $i;
}

以上所述就是本文的全部内容了,希望大家能够喜欢。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn