file_put_contents and fputs
2015-08-11 17:22
316 查看
test code
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
in append mode, fwrite()s are atomic (unless the size of
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.
<?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
handlewas fopen()ed
in append mode, fwrite()s are atomic (unless the size of
stringexceeds
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.
相关文章推荐
- 如何将两个有序链表合并成一个有序链表。
- iOS 身份证校验
- LeetCode:Edit Distance(字符串编辑距离DP)
- Android MVVM框架RoboBinding初探
- hdoj-2122 Ice_cream’s world III
- 软件人员推荐书目(一) 大师篇
- 视频流概念
- ListView显示多个的布局
- 【leetcode】209. Minimum Size Subarray Sum
- Handler-简介和用法
- 黑马程序员————反射
- JavaScript基础学习之-javascript权威指南--第八章函数闭包
- 再谈算法复杂度
- JAVA并发编程学习笔记之CAS操作
- Android之Inflate()方法用途
- TI BLE协议栈简介
- win10怎么通过历史记录恢复系统?
- 26-网络编程-09-网络编程(UDP协议-聊天程序)
- Android实例-使用电话拨号器在移动设备上(官方)(XE8+小米2)
- Python中库或者模组的解释