熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> PHP編程 >> 正文

PHP中fwrite與file

2022-06-13   來源: PHP編程 
這裡測試的是往文件中寫一百萬行記錄如果數據量很小比如條左右的記錄可能差距不大  

  function microtimeFloat() {
    list($usec$sec) = explode(" " microtime());
    return((float)$usec + (float)$sec);
}

  測試file_put_contents

復制代碼 代碼如下:
<?php
$userCount = ;
$itemCount = ;
$file = ratingstxt;
file_exists($file) &&unlink($file);

  $timeStart = microtimeFloat();
for ($i = ; $i < $userCount; $i++) {
    $uid =random();
    for ($j = ;$j < $itemCount; $j++) {
       $itemId = mt_rand( );
       $rating = $j == ? : mt_rand( ) / ;
       $line = sprintf("%s%d%s\n" $uid $itemId $rating);
       file_put_contents($file $line FILE_APPEND);
    }
}
$timeEnd = microtimeFloat();
echo sprintf("Spend time: |%s| second(s)\n" $timeEnd $timeStart);
?>

  測試結果:
測試過程中出現了打開文件的錯誤而且程序執行完成以後寫入的數據不完整只有漏了最重要的一點是時間花了秒多而用fwrite只花了秒多的時間差距還是不小的

  D:\myphp\research>php testphp
PHP Warning: file_put_contents(ratingstxt): failed to open stream:Permission
denied in D:\myphp\research\testphp on line

  Warning: file_put_contents(ratingstxt): failed to open stream:Permission denie
d in D:\myphp\research\testphp on line
Spend time: ||second(s)

  
:xDtLjaeDMGywifegZvRRQzVBZbbw
:xDtLjaeDMGywifegZvRRQzVBZbbw
:xDtLjaeDMGywifegZvRRQzVBZbbw
:xDtLjaeDMGywifegZvRRQzVBZbbw

  測試fwrite

復制代碼 代碼如下:
<?php
$userCount = ;
$itemCount = ;
$file = ratingstxt;
file_exists($file) &&unlink($file);

  $fp = @fopen($file ab);
if (!$fp) die("Open $file failed");

  $timeStart = microtimeFloat();
for ($i = ; $i < $userCount; $i++) {
    $uid =random();
    for ($j = ;$j < $itemCount; $j++) {
       $itemId = mt_rand( );
       $rating = $j == ? : mt_rand( ) / ;
       $line = sprintf("%s%d%s\n" $uid $itemId $rating);
       fwrite($fp $line);
       $k++;
    }
}
if ($fp) @fclose($fp);
$timeEnd = microtimeFloat();
echo sprintf("Spend time: |%s| second(s)\n" $timeEnd $timeStart);
?>

  測試結果:
寫一百萬行記錄秒左右寫完對於PHP來說速度算不錯了這是在我的個人電腦上面測試的如果在生產機上測試可能速度還要快一些
D:\myphp\research>php testphp
Spend time: ||second(s)

  用fwrite寫入的數據是完整的
QOvcZYFJFlFHjiGyGxAckOXdXYii
QOvcZYFJFlFHjiGyGxAckOXdXYii
QOvcZYFJFlFHjiGyGxAckOXdXYii
QOvcZYFJFlFHjiGyGxAckOXdXYii

  總結
如果要往文件裡面寫入大量的數據則推薦用fwrite不要用file_put_contents在高並發的請求中也建議用fwrite


From:http://tw.wingwit.com/Article/program/PHP/201311/21319.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.