PHP 寫檔案加鎖的例子

來源:互聯網
上載者:User

用 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 進行寫檔案加鎖,防止並發同時操作一個檔案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.