PHP efficiently counts the number of lines in large files

*文
Release: 2023-03-18 15:08:02
Original
2010 people have browsed it

How to efficiently count the number of lines in large files in php? This article mainly shares examples of ultra-fast and efficient counting of lines in large files in PHP. I hope to be helpful.

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

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

Test situation, file size 3.14 GB

1st time: line: 13214810, time:56.2779 s;
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; }
Copy after login

Related recommendations:

PHP file reading fread, fgets, fgetc, file_get_contents and Example code for using the file function

PHP file itself operation

PHP file reading to array

The above is the detailed content of PHP efficiently counts the number of lines in large files. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!