1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<?php #SPL是Standard PHP Library(PHP标准库)的缩写。 #包括:数据结构、迭代器、接口、异常、函数、文件处理等 #比较使用spl遍历文件行、以及通过php自带的file函数遍历文件行 #spl由于使用了迭代器,所以在内存上消耗更小,但是速度明显更慢 #个人感觉spl只是方便了代码操作,提供了一种面向对象的写法 #但是实际应用中可以使用分批读然后释放来从速度跟内存消耗上超越spl #test.txt 大小:12480kb 行数:245760 set_time_limit(0); define('MEMORY_LIMIT_ON', true); //SplFileObject G('begin'); $arr = new SplFileObject('D:\wnmp\www\public\test\test.txt'); $str = ''; foreach( $arr as $line) { $str .= $line; } G('end'); echo G('begin', 'end', 3); echo '<br>'; echo G('begin', 'end', 'm'); // 3次测试的时间和内存 // 时间:1.733 内存:12,490 // 时间:1.741 内存:12,490 // 时间:1.741 内存:12,490 //file G('begin'); $arr = file('D:\wnmp\www\public\test\test.txt'); $str = ''; foreach ($arr as $key => $value) { $str .= $value; } G('end'); echo G('begin', 'end', 3); echo '<br>'; echo G('begin', 'end', 'm'); // 3次测试的时间和内存 // 时间:0.112 内存:62,530 // 时间:0.114 内存:62,530 // 时间:0.113 内存:62,530 /** * 使用thinkphp的统计方法 */ function G($start,$end='',$dec=4) { static $_info = array(); static $_mem = array(); if(is_float($end)) { // 记录时间 $_info[$start] = $end; }elseif(!empty($end)){ // 统计时间和内存使用 if(!isset($_info[$end])) $_info[$end] = microtime(TRUE); if(MEMORY_LIMIT_ON && $dec=='m'){ if(!isset($_mem[$end])) $_mem[$end] = memory_get_usage(); return number_format(($_mem[$end]-$_mem[$start])/1024); }else{ return number_format(($_info[$end]-$_info[$start]),$dec); } }else{ // 记录时间和内存使用 $_info[$start] = microtime(TRUE); if(MEMORY_LIMIT_ON) $_mem[$start] = memory_get_usage(); } return null; } //官方地址:http://php.net/manual/zh/book.spl.php //参考博客:http://www.ruanyifeng.com/blog/2008/07/php_spl_notes.html |