日期:2011-11-30  浏览次数:20453 次

 

  从PHP5.1开始,PHP提供了用户对Zend VM执行分发方式的选择接口.

  之前的文章中, 我也提过这方面的内容, Zend虚拟机在执行的时候, 对于编译生成的op_array中的每一条opline的opcode都会分发到相应的处理器(zend_vm_def.h定义)执行, 而按照分发的方式不同, 分发过程可以分为CALL, SWITCH, 和GOTO三种类型.

  默认是CALL方式, 也就是所有的opcode处理器都定义为函数, 然后虚拟机调用. 这种方式是传统的方式, 也一般被认为是最稳定的方式.

  SWITCH方式和GOTO方式则和其命名的意义相同, 分别通过switch和goto来分发opcode到对应的处理逻辑(段).

  官方给出的描述是:

  CALL – Uses function handlers for opcodes

  SWITCH – Uses switch() statement for opcode dispatch

  GOTO – Uses goto for opcode dispatch (threaded opcodes architecture)

  GOTO is usually (depends on CPU and compiler) faster than SWITCH, which

  tends to be slightly faster than CALL.

  CALL is default because it doesn’t take very long to compile as opposed

  to the other two and in general the speed is quite close to the others.

  那么如果使用GOTO方式, 效率上到底能提高多少呢?

  今天我就分别使用各种方式来测试一番, 测试脚本bench.php.

  第一点被证明的就是, 官方说的GOTO方式编译耗时显著高于其他俩种方式, 我一开始在虚拟机上编译, 每次都Hangup(囧), 最后只好换了个强劲点的物理机, 大约3分钟后, 编译成功..

  测试环境:

 

  PHP 5.3.0 Linux

  AMD Opteron(tm) Processor 270(2G) X 4 6G Memory

 

  编译参数:

 

  ./configure --with-zend-vm=CALL/GOTO/SWITCH

 

  测试结果如下(都是三次取中值):

  CALL方式:

 

  laruence@dev01.tc$ sapi/cli/php bench.php

  simple 0.358

  simplecall 0.418

  simpleucall 0.405

  simpleudcall 0.424

  mandel 1.011

  mandel2 1.238

  ackermann(7) 0.375

  ary(50000) 0.083

  ary2(50000) 0.075

  ary3(2000) 0.561

  fibo(30) 1.156

  hash1(50000) 0.114

  hash2(500) 0.091

  heapsort(20000) 0.270

  matrix(20) 0.276

  nestedloop(12) 0.599

  sieve(30) 0.350

  strcat(200000) 0.039

  ------------------------

  Total 7.844

 

  SWITCH方式:

 

  laruence@dev01.tc$ sapi/cli/php bench.php

  simple 0.393

  simplecall 0.414

  simpleucall 0.424

  simpleudcall 0.445

  mandel 1.007

  mandel2 1.254

  ackermann(7) 0.392

  ary(50000) 0.084

  ary2(50000) 0.073

  ary3(2000) 0.593

  fibo(30) 1.185

  hash1(50000) 0.120

  hash2(500) 0.092

  heapsort(20000) 0.285

  matrix(20) 0.295

  nestedloop(12) 0.678

  sieve(30) 0.359

  strcat(200000) 0.042

  ------------------------

  Total 8.138

 

  GOTO方式 :

 

  laruence@dev01.tc$ sapi/cli/php bench.php

  simple 0.306

  simplecall 0.373

  simpleucall 0.369

  simpleudcall 0.385

  mandel 0.879

  mandel2 1.132

  ackermann(7) 0.356

  ary(50000) 0.081

  ary2(50000) 0.073

  ary3(2000) 0.525

  fibo(30) 1.043

  hash1(50000) 0.111

  hash2(500) 0.088

  heapsort(20000) 0.247

  matrix(20) 0.247

  nestedloop(12) 0.519

  sieve(30) 0.331

  strcat(200000) 0.037

  ------------------------

  Total 7.103

 

  可见, GOTO方式最快, SWITCH方式最慢.和官方的描述稍有不符.

  GOTO方式比其默认的CALL方式, 性能提升还是比较明显的.

  所以, 如果你希望让PHP发挥到机制, 改变Zend VM的分发方式, 也可以做为一个考虑因素.

  附:

  使用GOTO方式的configure选项:

 

  --with-zend-vm=GOTO

 

  也可以在Zend目录下使用:

 

  php zend_vm_gen.php --with-vm-kind=[CALLGOTOSWITH]

 

  测试脚本bench.php<