file_put_contents and fputs

来源:互联网 发布:淘宝开店认证在哪里弄? 编辑:程序博客网 时间:2024/05/21 09:46

test code

<?phpfile_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.



0 0
原创粉丝点击