技术开发 频道

对PHP采集数据提取核心函数的速度测试与分析

  【IT168 技术】由于程序需要,于是对PHP采集中的字符提取的核心部分进行了执行速度的测试。

  测试了三种最常见的提取办法:

  方法一:

<?php
  require
"class.debug.php";
  
function getContent ( $sourceStr )
  {
  $content
= strstr( $sourceStr, '形' );
  $content = substr( $content, 0, strrpos( $content, '言' ) + strlen( '言' ) );
  return $content;
  }
  $sourceStr
= '拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论';
  $debug = new Debug;
  $debug
->startTimer();
  
for( $i = 0; $i < 1000000; $i++ )
  {
  $returnStr
= getContent( $sourceStr );
  }
  $timeInfo
= $debug->endTimer();
  echo $timeInfo;
  ?
>

  通过比较低级的字符操作函数进行提取.

  方法二:

 

<?php
  require
"class.debug.php";
  
function getContent ( $sourceStr )
  {
  $pattern
= "/形(.*?)言/is";
  preg_match_all( $pattern, $sourceStr, $result );
  return $result[
1][0];
  }
  $sourceStr
= '拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论';
  $debug = new Debug;
  $debug
->startTimer();
  
for( $i = 0; $i < 1000000; $i++ )
  {
  $returnStr
= getContent( $sourceStr );
  }
  $timeInfo
= $debug->endTimer();
  echo $timeInfo;
  ?
>

  使用一个简单的正则来提取.

  方法三:

<?php  
  require
"class.debug.php";
  
function getContent ( $sourceStr )
  {
  $content
= explode( '形', $sourceStr );
  $content = explode( '言', $content[1] );
  return $content[0];
  }
  $sourceStr
= '拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论';
  $debug = new Debug;
  $debug
->startTimer();
  
for( $i = 0; $i < 1000000; $i++ )
  {
  $returnStr
= getContent( $sourceStr );
  }
  $timeInfo
= $debug->endTimer();
  echo $timeInfo;
  ?
>

 

  通过两次explode分裂字符串来提取.

  测试前我的观点是: 1 > 2 > 3

  在两台电脑上进行测试,每台测试了两次,结果如下:

  (1)17.32061

  (2)26.81763

  (3)17.53692

  (1)17.87291

  (2)26.88415

  (3)17.10972

  (1)11.30147

  (2)20.25284

  (3)11.54464

  (1)11.69471

  (2)21.19316

  (3)11.72613

  So,最终结果不是我想的那样,第一种和第三种方法的速度相当.第二种方法消耗时间大约是第一,三种的两倍.

  看来正则由于匹配的原因速度是最慢的,而explode由于两次的分裂,虽然速度上不慢,但是资源消耗比第一种方法多,毕竟是分裂了两次,都是分裂到数组,开销比纯粹的简单字符函数处理要来得大.

  综上,推荐使用方法一.

  有兴趣的朋友可以自己测试下:

  <?php

  class Debug

  {

  
function startTimer()

  {

  global $starttime;

  $mtime
= microtime ();

  $mtime
= explode (' ', $mtime);

  $mtime
= $mtime[1] + $mtime[0];

  $starttime
= $mtime;

  }

  
function endTimer()

  {

  global $starttime;

  $mtime
= microtime ();

  $mtime
= explode (' ', $mtime);

  $mtime
= $mtime[1] + $mtime[0];

  $endtime
= $mtime;

  $totaltime
= round (($endtime - $starttime), 5);

  return $totaltime;

  }

  }

  ?
>
0
相关文章