您的位置:首页 > 其它

file_put_contents and fputs

2015-08-11 17:22 316 查看
test code

<?php

file_put_contents('/tmp/test.log',"");

$workers = 100;

for ($i = 0; $i < $workers; ++$i) {
$pid = pcntl_fork();

if (!$pid) {
process($i);
exit($i);
}
}

while (pcntl_waitpid(0, $status) != -1) {
$status = pcntl_wexitstatus($status);
echo "Child $status completed\n";
}

echo "ok";

function process($i)
{
$n = 10000;
while ($n > 0) {
file_put_contents('/tmp/test.log', "{$i} {$n} \n", FILE_APPEND);
$n--;
}
}

function _process($i)
{
$fp = fopen('/tmp/test.log', 'a');
$n = 10000;
while ($n > 0) {
fputs($fp, "{$i} {$n} \n");
$n--;
}
fclose($fp);
}


run

time php file_test.php

file_put_contests

ok

real 0m21.648s

user 0m6.740s

sys 0m11.333s

fputs

ok

real 0m4.599s

user 0m1.572s

sys 0m3.128s

由此可以看出fput比file_put_contents要快4倍左右

在web app中经常要记录一些日志,一次请求中可能要几率好几条日志,可见用puts是比较优的方法

另外

我发现很多人喜欢在最加文件内容时加锁 flock,其实没有必要,fwrite是原子性的

Note:

If
handle
was fopen()ed
in append mode, fwrite()s are atomic (unless the size of
string
exceeds
the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a
resource before calling fwrite(); all of the data will be written without interruption.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: