欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP中fwrite与file_put_contents性能测试代码

程序员文章站 2023-01-07 18:49:34
function microtimefloat() {    list($usec,$sec) = explode(" ", microtim...

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

1.测试file_put_contents

复制代码 代码如下:

<?php
$usercount = 1000;
$itemcount = 1000;
$file = 'ratings.txt';
file_exists($file) &&unlink($file);

$timestart = microtimefloat();
for ($i = 0; $i < $usercount; $i++) {
    $uid =random(32);
    for ($j = 0;$j < $itemcount; $j++) {
       $itemid = mt_rand(1, 300000);
       $rating = $j == 0 ? 1 : mt_rand(1, 100) / 100;
       $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);
?>

测试结果:
测试过程中出现了打开文件的错误,而且程序执行完成以后写入的数据不完整,只有999997行,漏了3行。最重要的一点是时间花了307秒多,而用fwrite只花了10秒多的时间,差距还是不小的。

d:\myphp\research>php test2.php
php warning: file_put_contents(ratings.txt): failed to open stream:permission
denied in d:\myphp\research\test2.php on line 79

warning: file_put_contents(ratings.txt): failed to open stream:permission denie
d in d:\myphp\research\test2.php on line 79
spend time: |307.0586669445|second(s)

...
999994:98xdtljaed8mg9ywifegzvrrqzvbzbbw,167670,0.15
999995:98xdtljaed8mg9ywifegzvrrqzvbzbbw,234223,0.13
999996:98xdtljaed8mg9ywifegzvrrqzvbzbbw,84947,0.79
999997:98xdtljaed8mg9ywifegzvrrqzvbzbbw,6489,0.38

2.测试fwrite

复制代码 代码如下:

<?php
$usercount = 1000;
$itemcount = 1000;
$file = 'ratings.txt';
file_exists($file) &&unlink($file);

$fp = @fopen($file, 'ab');
if (!$fp) die("open $file failed");

$timestart = microtimefloat();
for ($i = 0; $i < $usercount; $i++) {
    $uid =random(32);
    for ($j = 0;$j < $itemcount; $j++) {
       $itemid = mt_rand(1, 300000);
       $rating = $j == 0 ? 1 : mt_rand(1, 100) / 100;
       $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);
?>

测试结果:
写一百万行记录,10秒左右写完,对于php来说,速度算不错了。这是在我的个人电脑上面测试的,如果在生产机上测试,可能速度还要快一些。
d:\myphp\research>php test2.php
spend time: |10.764221191406|second(s)

用fwrite写入的数据是完整的
999997,qovczyfjflfhjigygxac615koxdx3yii,246982,0.03
999998,qovczyfjflfhjigygxac615koxdx3yii,240160,0.39
999999,qovczyfjflfhjigygxac615koxdx3yii,46296,0.61
1000000,qovczyfjflfhjigygxac615koxdx3yii,26211,0.14

3.总结
如果要往文件里面写入大量的数据,则推荐用fwrite,不要用file_put_contents。在高并发的请求中也建议用fwrite。