php 给文件加锁,PHP 写文件加锁

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

}

如图所示:

3efe38997eb2f2e867e0540c6e06bd21.png

耗时 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));

}

运行效果如图:

a50974db0f19ff0b88d48aa836516580.png

如图所示,耗时 40.46 s,大大提高了效率。

跟 file_put_contents 函数比, fwrite 提高了写文件的效率,同时使用 flock 进行写文件加锁,防止并发同时操作一个文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值