python

导航

php和python哪个效率高?

来源 :中华考试网 2020-10-12

  Python和php都有自己效率最高的部分,其中以下两个方面php效率更高!

  废话不多说,亮代码。

  python执行

  import re

  import urllib

  import time

  start = time.clock()

  for i in range(1,100000):

  z = i+1

  print z

  end = time.clock()

  print (end-start)

  耗时:0.011912s

  PHP执行

  

  $z = 0;

  $t1 = microtime(true);

  for ($i=0; $i < 100000; $i++) {

  $z = $z+1;

  $t2 = microtime(true);

  echo $t2-$t1;

  ?>

  耗时:0.002054s

  结论:PHP效率完胜Python。

  且慢,这就完了么,不然。

  python机制和PHP不同,处理数字时会对-5-100的数字进行cache,建立所有数字对象,所以会慢,这个代码显然对python不公平。

  换成正则代码,正则是爬虫最常用的,这个正式python的强项,同样的算法,看一下效果如何。

  简单起见,用变量$html或html表示已经获取到的html代码

  Python

  start = time.clock()

  reg = r'src="https://www.examw.com/(.+?\.jpg)" pic_ext'

  imgre = re.compile(reg)

  imglist = re.findall(imgre,html)

  end = time.clock()

  print (end-start)

  执行耗时0.004s

  PHP

  $t1 = microtime(true);

  preg_match_all("/src=\"(.*?).jpg\"/i", $html ,$title);

  $t2 = microtime(true);

  执行耗时0.002s

  效率可见。但只这样来下结论未免草率,可能还有很多算法中python的处理要优于PHP,但我们普通的需求,还不足以去比拼由各语言特性所受影响的深层算法。

  所以开始写爬虫还是用PHP进行来的比较快,免去了python的学习成本,效率并不比python差。

分享到

相关资讯