最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
PHP 写文件加锁的例子
时间:2022-06-24 22:44:16 编辑:袖梨 来源:一聚教程网
用 PHP 的 file_put_contents 函数以追加的方式,循环 10 w 次写文件,耗时很多。因为 file_put_contents 函数每次都要打开文件,写入文件,然后关闭文件。
以下是测试:
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));
}
如图所示:

耗时 165.76 秒。现在换一种写文件的方式,使用 fwrite 并且加锁的方式同样循环 10w 次写入,代码如下:
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));
}
运行效果如图:

如图所示,耗时 40.46 s,大大提高了效率。
跟 file_put_contents 函数比, fwrite 提高了写文件的效率,同时使用 flock 进行写文件加锁,防止并发同时操作一个文件。
相关文章
- poipiku网站如何打开-poipiku官网网页版访问入口 01-06
- uc网盘网页版官方入口-UC网盘网页版快捷登录 01-06
- 全免费影视软件哪个最好用-全免费电视电影软件推荐 01-06
- 悟空浏览器怎样直接打开网页-悟空浏览器一键直达网页技巧分享 01-06
- 谷歌google官方入口-Google官方网站入口 01-06
- 漫画天堂最新版本下载入口-漫画天堂官方正版下载入口汇总 01-06