PHP性能优化

性能问题浅析

PHP的性能问题在整个项目的性能问题中占比30%-40%,不到50%。 优化项目不局限于优化PHP。


产生性能问题的原因

  • PHP语法使用不当
  • 使用PHP语言做了不擅长的事情
  • 使用PHP语言连接的服务不给力
  • PHP自身的短板,PHP需要解析为底层语言:PHP --> C语言 --> 汇编语言,每次请求都需要处理一遍。
  • 具体问题具体分析

知识点

graph LR
A(php文件)-->|Scanner| B(Exprs)
B-->|Parser| C(Opcodes)
C-->|Exec| D(Output)

PHP文件经Zend引擎逐行扫描,保存成Zend引擎能识别的语法Exprs。然后经过解析生成Opcodes,再执行Opcode,产生结果。

PHP缓存的对象是Opcode


性能问题解决方案

  • PHP语言级的优化(易)
  • PHP周边的性能优化(数据库, 服务器, 缓存等)(难)
  • PHP语言自身分析, 优化(底层)(较难)

压力测试工具简介 Apache Benchmark(ab)

  • 简介:ab是由Apache提供的压力测试软件。安装Apache时服务器会自带该压测软件。

  • 使用方法:

./ab -n 1000 -c 100 http://www.baidu.com/   注意如果不是请求某个具体文件,则必须添加最后的斜杠
     -n 请求数
             -c 并发数
                    URL 目标压测地址
  • 安装方法:在安装Apache时已经附带安装

  • 返回结果

//服务器信息
Server Software:        BWS/1.1
Server Hostname:        www.baidu.com
Server Port:            80

//文档信息
Document Path:          /
Document Length:        111326 bytes

//连接信息
Concurrency Level:      10
Time taken for tests:   0.333 seconds   //整个测试持续时间
Complete requests:      100 //完成的请求数量
Failed requests:        97  //模拟请求中失败的请求数量
   (Connect: 0, Receive: 0, Length: 97, Exceptions: 0)
Total transferred:      11240793 bytes //模拟请求中传输的总数据量,包含标头数据
HTML transferred:       11145902 bytes //模拟请求中正文数据总量
Requests per second:    300.25 [#/sec] (mean) //每秒支持的请求总数
Time per request:       33.306 [ms] (mean) //满足一个请求花费的总时间
Time per request:       3.331 [ms] (mean, across all concurrent requests)
Transfer rate:          32959.33 [Kbytes/sec] received //m每秒接收到的字节总数

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        1    1   0.4      1       2
Processing:    18   30   6.7     26      44
Waiting:        9   13   3.8     11      26
Total:         19   31   6.7     28      45

Percentage of the requests served within a certain time (ms)
  50%     28
  66%     31
  75%     36
  80%     40
  90%     42
  95%     43
  98%     44
  99%     45
 100%     45 (longest request)

在优化中Requests per second的值要尽可能的大,Time per request的值要尽可能小。


PHP语言级性能优化

  • 尽量使用PHP自身的内置变量、常量、函数

自写代码冗余较多,可读性不强,并且降低性能。

内容来源于网络或书籍
原文地址:https://www.cnblogs.com/my3306/p/9712490.html