Home >Backend Development >PHP Tutorial >PHP is super fast and efficient to count the number of lines in large files, _PHP tutorial

PHP is super fast and efficient to count the number of lines in large files, _PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:47:20885browse

php is super fast and efficient to count the number of lines in large files.

Use php to get the number of lines in a file. The answer given on the Internet is usually to use file to read it all at once, which is not easy Suitable for large files. Usually, people use while loop to count line by line for large files, but this is too slow

The fastest method is to count multiple lines, read N bytes each time, and then count the number of lines. This is much more efficient than line by line.

Test situation, file size 3.14 GB

The 1st time: line: 13214810, time:56.2779 s;
The 2nd time: 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;
}

The above is the entire content of this article, I hope you all like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1027050.htmlTechArticlephp is super fast and efficient to count the number of lines in large files. Use php to get the number of file lines. The answers given on the Internet are usually It uses file to read it all at once, which is not suitable for large files. Usually large files are large...
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