PHP Write file plus lock example

Source: Internet
Author: User
Tags flock php write

Using PHP's file_put_contents function to append, it takes a lot of time to write a file in the loop. Because the File_put_contents function opens the file each time, writes the file, and then closes the file.

Here is the test:

Public function handle ()
{
$TESTTXT = Storage_path (' test.txt ');
for ($i = 0; $i < 100000; $i + +) {
$this->comment (' writing ... ');
File_put_contents ($testTxt, ' Wo shi Tanteng. ') Php_eol, File_append);
}
$this->comment (' Time: '. Round (Microtime (true)-Laravel_start, 2));
}
As shown in the figure:


Takes 165.76 seconds. Now the way to write a file, use the fwrite and lock the same way to cycle the 10w write, the code is as follows:

Public function handle ()
{
$TESTTXT = Storage_path (' test2.txt ');
$handle = fopen ($testTxt, ' WR ');
Flock ($handle, LOCK_EX | LOCK_NB);
for ($i = 0; $i < 100000; $i + +) {
$this->comment (' writing ... ');
Fwrite ($handle, ' Wo shi Tanteng. ') PHP_EOL);
}
Flock ($handle, lock_un);
Fclose ($handle);
$this->comment (' Time: '. Round (Microtime (true)-Laravel_start, 2));
}
Operation Effect as shown:


As shown in the figure, the time consuming 40.46 S has greatly improved the efficiency.

Compared with the file_put_contents function, fwrite improves the efficiency of writing files while using flock to write files and locks to prevent concurrent operation of a file.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.