对php采集数据提取核心函数的速度的测试与分析
由于程序需要,于是对PHP采集中的字符提取的核心部分进行了执行速度的测试。
原文地址:http://www.phpchina.com/index.php?action-viewnews-itemid-946
由于程序需要,于是对PHP采集中的字符提取的核心部分进行了执行速度的测试。
测试了三种最常见的提取办法:
方法一、
PHP代码 <?php 2. 3. require "class.debug.php"; 4. 5. function getContent ( $sourceStr ) 6. { 7. $content = strstr( $sourceStr, '形' ); 8. $content = substr( $content, 0, strrpos( $content, '言' ) + strlen( '言' ) ); 9. 10. return $content; 11. } 12. 13. $sourceStr = '拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论'; 14. 15. $debug = new Debug; 16. 17. $debug->startTimer(); 18. 19. for( $i = 0; $i < 1000000; $i++ ) 20. { 21. $returnStr = getContent( $sourceStr ); 22. } 23. 24. $timeInfo = $debug->endTimer(); 25. 26. echo $timeInfo; 27. 28. ?> 通过比较低级的字符操作函数进行提取.
方法二、
PHP代码 1. <?php 2. 3. require "class.debug.php"; 4. 5. function getContent ( $sourceStr ) 6. { 7. $pattern = "/形(.*?)言/is"; 8. preg_match_all( $pattern, $sourceStr, $result ); 9. return $result[1][0]; 10. } 11. 12. $sourceStr = '拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论'; 13. 14. $debug = new Debug; 15. 16. $debug->startTimer(); 17. 18. for( $i = 0; $i < 1000000; $i++ ) 19. { 20. $returnStr = getContent( $sourceStr ); 21. } 22. 23. $timeInfo = $debug->endTimer(); 24. 25. echo $timeInfo; 26. 27. ?> 使用一个简单的正则来提取.
方法三、
第三种方法最高效
PHP代码 1. <?php 2. 3. require "class.debug.php"; 4. class v 5. { 6. var $content; 7. function getContent ( $sourceStr ) 8. { 9. list($this->content,) = explode( '形', $sourceStr,2 ); 10. list(,$this->content) = explode( '言', $this->content ,2); 11. 12. return $this->content; 13. 14. } 15. } 16. 17. $sourceStr = '拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论'; 18. 19. $debug = &new Debug; 20. 21. $debug->startTimer(); 22. 23. for( $i = 0; $i < 1000000; $i++ ) 24. { 25. $returnStr = $v->getContent( $sourceStr ); 26. } 27. 28. $timeInfo = $debug->endTimer(); 29. 30. echo $timeInfo; 31. 32. ?> 通过两次explode分裂字符串来提取.
,第一种和第三种方法的速度相当.第二种方法消耗时间大约是第一,三种的两倍.
测试时间函数
PHP代码 class.debug.php 1. <?php 2. 3. class Debug 4. { 5. function startTimer() 6. { 7. global $starttime; 8. $mtime = microtime (); 9. $mtime = explode (' ', $mtime); 10. $mtime = $mtime[1] + $mtime[0]; 11. $starttime = $mtime; 12. } 13. 14. function endTimer() 15. { 16. global $starttime; 17. $mtime = microtime (); 18. $mtime = explode (' ', $mtime); 19. $mtime = $mtime[1] + $mtime[0]; 20. $endtime = $mtime; 21. $totaltime = round (($endtime - $starttime), 5); 22. return $totaltime; 23. } 24. } 25. ?> 这种方法是最快的!
PHP代码 1. <?php 2. function cut($str,$start,$end) 3. { 4. $contents=strstr($str,$start); 5. $contents=substr_replace($contents,'',strpos($contents,$end)).$end; 6. return $contents; 7. } 8. ?>