PHP7.4启用opcache并进行基准测试

启用

/path/to/7.4/php.ini

[opcache]

zend_extension=opcache.so

; 1.启用,默认禁用
opcache.enable=1

; 是否用于cli,同opcache.enable
opcache.enable_cli=1

; 由于我希望在php-fpm启动后,不检查文件的变化(减少没必要的资源开支),这里我设置为0;如果设置为1,那么opcache.revalidate_freq生效
opcache.validate_timestamps=0

; 注意这里我注释了,1.表示每秒检查文件变化,0表示每个请求都检查文件变化
; opcache.revalidate_freq=2

重启php-fpm:

kill -usr2 $(cat /path/to/php-fpm@7.4.pid)

使用ab命令测试效果

这是我的测试代码:

// plus.php
<?php

for($i=0, $total = 0;$i<=10000000;$i++){
    $total += $i;
}

echo $total;

ab命令如下:

ab -c 5 -n 50 'https://blog.yeskn.com/plus.php'

开启之前:

Document Path:          /plus.php
Document Length:        14 bytes

Concurrency Level:      5
Time taken for tests:   3.745 seconds
Complete requests:      50
Failed requests:        0
Total transferred:      7800 bytes
HTML transferred:       700 bytes
Requests per second:    13.35 [#/sec] (mean)
Time per request:       374.523 [ms] (mean)
Time per request:       74.905 [ms] (mean, across all concurrent requests)
Transfer rate:          2.03 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       27   34   3.9     33      43
Processing:   147  317  74.9    300     443
Waiting:      146  317  74.9    300     443
Total:        189  350  74.7    333     476

Percentage of the requests served within a certain time (ms)
  50%    333
  66%    389
  75%    418
  80%    435
  90%    469
  95%    471
  98%    476
  99%    476
 100%    476 (longest request)

开启之后:

Document Path:          /plus.php
Document Length:        14 bytes

Concurrency Level:      5
Time taken for tests:   2.467 seconds
Complete requests:      50
Failed requests:        0
Total transferred:      7800 bytes
HTML transferred:       700 bytes
Requests per second:    20.27 [#/sec] (mean)
Time per request:       246.721 [ms] (mean)
Time per request:       49.344 [ms] (mean, across all concurrent requests)
Transfer rate:          3.09 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       27   34   4.6     33      47
Processing:   102  197  52.4    188     295
Waiting:      101  197  52.4    188     295
Total:        135  231  52.2    229     327

Percentage of the requests served within a certain time (ms)
  50%    229
  66%    266
  75%    279
  80%    285
  90%    300
  95%    311
  98%    327
  99%    327
 100%    327 (longest request)

可以看到,QPS提升了大概0.5倍,并且速度提升很大,启用opcache后,最慢的请求只有327ms,没启用时,50%的请求都要大于333ms,提升效果显著。

以上测试用的是默认配置,如果进行合理的配置,我相信优化会更加明显!

发表评论

电子邮件地址不会被公开。 必填项已用*标注