Heim  >  Artikel  >  Backend-Entwicklung  >  php超快高效率统计大文件行数,_PHP教程

php超快高效率统计大文件行数,_PHP教程

WBOY
WBOYOriginal
2016-07-13 09:47:20790Durchsuche

php超快高效率统计大文件行数,

用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;
}

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1027050.htmlTechArticlephp超快高效率统计大文件行数, 用php获取文件行数,网上给出的答案通常是使用file这样一次性读取,这样不适用在大文件。通常大文件大...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn