search
HomeBackend DevelopmentPHP TutorialUse XHProf and XHGui to analyze PHP running performance under Linux system_php skills

What is performance analysis?
Performance analysis measures the relative performance of an application at the code level. Events that performance analysis will capture include: CPU usage, memory usage, function call duration and number, and call graph. The behavior of profiling also affects application performance.
When should performance analysis be performed?
When considering whether to perform performance analysis, you first need to ask: Does the application have performance problems? If so, you need to consider further: How big is the problem?

If you don’t do this, you will fall into the trap of optimizing prematurely, which may waste your time.

To determine whether your application has performance issues, you should determine performance goals. For example, the response time for 100 concurrent users is less than 1s. Then, you need to benchmark to see if you achieve this goal. A common mistake is to perform benchmarking in a development environment. In fact, you have to benchmark in production. (Actual production environment or simulated production environment, the latter is easily implemented in SaaS.
There are many products for benchmarking, including ab, siege and JMeter. I personally prefer JMeter's feature set, but ab and siege are easier to use.

Once you determine that your application has a performance issue, you need to analyze its performance, implement improvements, and then benchmark again to see if the issue is resolved. After every change, you should benchmark it to see the effect. If you make a lot of changes and notice that your application's performance is slowing down, you won't be able to pinpoint which change caused the problem.

The following picture is the performance life cycle I defined:

2015128164631254.png (1808×1620)

Common causes of performance degradation
Some of the common causes of performance degradation are quite surprising. Even with a high-level language like PHP, the quality of the code is rarely the root of the problem. With today's hardware configurations, the CPU is rarely the cause of performance limitations. The common reasons are:

Data Storage

  • PostgreSQL
  • MySQL
  • Oracle
  • MSSQL
  • MongoDB
  • Riak
  • Cassandra
  • Memcache
  • CouchDB
  • Redis

External Resources

  • APIs
  • File System
  • Network Interface
  • External Process
  • Bad code

Which performance analyzer to choose?
In the PHP world, there are two distinct profilers - active and passive.

Active VS Passive Performance Analysis
Active analyzers are used during development and are enabled by developers. Active analyzers collect more information than passive analyzers and have a greater impact on performance. Typically, active analyzers cannot be used in production environments. XDebug is an active analyzer.

Because active analyzers cannot be used in production environments, Facebook launched a passive analyzer - XHProf. XHProf is built for use in production environments. It has minimal impact on performance while gathering enough information to diagnose performance issues. XHProf and OneAPM are both passive profilers.

Typically, the additional information collected by XDebug is not necessary for general performance problem analysis. This means that passive profilers are a better choice for ongoing performance analysis, even in a development environment.

XHProf XHGui
XHProf was developed by Facebook and includes a basic user interface for viewing performance data. Additionally, Paul Reinheimer developed XHGui and an enhanced user interface (UI) for viewing, comparing, and analyzing performance data.

Installation
Install XHProf
XHProf can be installed via PECL, follow these steps:

$ pecl install xhprof-beta

The pecl command will attempt to automatically update your php.ini settings. The file pecl is trying to update can be found using:

$ pecl config-get php_ini

It will add a new configuration line at the top of the specified file (if any). You may want to move them to a more suitable location.

Once you compile the extension, you must enable it. To do this, you need to add the following code to your PHP INI file:

[xhprof]
extension=xhprof.so 

Afterwards, performance analysis and inspection can be easily performed with XHGui.

Install XHGui
To install XHGui, you must get it directly from git. The project can be found on github at: https://github.com/perftools/xhgui

XHGui Requirements:

  • PHP 5.3
  • ext/mongo
  • composer
  • MongoDB (optional if you only need to collect data; required if data analysis is required)

First, clone the project to any location. On Debian-based Linux systems (such as Ubuntu, etc.), it may be /var/www. On Mac OS X, this might be /Library/WebServer/Documents.

$ cd /var/www
$ git clone https://github.com/perftools/xhgui.git
$ cd xhgui
$ php install.php

最后一个命令是运行 composer 以安装依赖并检查 XHGui 缓存目录的权限。如果失败,你可以手动运行 composer install。

下一步,你可能需要创建配置文件。这一步很容易实现,可以使用在 /path/to/XHGui/config/config.default.php 下的默认配置文件。

如果你在本地运行 MongoDB,没有身份验证,则可能不需要这样做。因为它将回退为默认值。而在多服务器环境中,你会需要一个所有服务器都能进行存储的远程 MongoDB 服务器,并进行恰当的配置。

为提高 MongoDB 的性能,你可以运行以下指令以添加索引:

$ mongo
> use xhprof
db.results.ensureIndex( { 'meta.SERVER.REQUEST_TIME' : -1 } ) 
db.results.ensureIndex( { 'profile.main().wt' : -1 } ) 
db.results.ensureIndex( { 'profile.main().mu' : -1 } ) 
db.results.ensureIndex( { 'profile.main().cpu' : -1 } ) 
db.results.ensureIndex( { 'meta.url' : 1 } ) 

其他配置
如果你不想在生产环境中安装 mongo ,或无法让 Web 服务器访问 mongo 服务器,您可以将性能分析数据保存在磁盘中,再导入到本地 MongoDB 供以后分析。

为此,请在 config.php 中进行以下修改:

<&#63;php 
'save.handler' = 'file', 
'save.handler.filename' => '/path/to/xhgui/xhprof-' .uniqid("", true). '.dat', 
&#63;>

改变文件中的 save.handler,然后取消批注 save.handler.filename ,为其赋一个恰当的值。

注意:默认每天只保存一个分析文件。

一旦分析数据的准备就绪,你就可以使用 XHGui 附带的脚本导入之:

$php /path/to/xhgui/external/import.php /path/to/file.dat

在此之后的步骤都相同。

运行 XHGui
XHGui 是以 PHP 为基础的 Web 应用程序,你可以以 /path/to/xhgui/webroot 为根文件,设置一个标准的虚拟主机。

或者,你可以简单地使用 PHP 5.4+ cli-server 例如:

$ cd /path/to/xhgui
$ php -S 0:8080 -t webroot/

这将使 XHGui 在所有网络接口都可通过 8080 端口进行通信。

运行性能分析器
运行分析器时,你需要在待分析的所有页面包含 external/header.php 脚本。为此,你可以在 PHP ini 文件设置 auto_prepend_file 。你既可以直接在公共 INI 文件进行设置,也可以限制到单一的虚拟主机。

对于 Apache 服务器,添加以下代码:

php_admin_value auto_prepend_file "/path/to/xhgui/external/header.php"

对于 Nginx 服务器,在服务器配置中添加以下代码:

fastcgi_param PHP_VALUE "auto_prepend_file=/path/to/xhgui/external/header.php";

如果您使用 PHP 5.4+ cli-server(PHP -S),则必须通过命令行标记进行设置:

$ php -S 0:8080 -dauto_prepend_file=/path/to/xhgui/external/header.php

默认情况下,分析器运行时只分析(大约) 1% 的请求。这是由以下 external/header.php 代码控制的:

<&#63;php 
if (rand(0, 100) !== 42) { 
  return;
}
&#63;>

如果你想分析每一个请求(例如,在开发阶段),你可以将这段代码注释掉。如果你想让分析 10% 的请求,你可以做如下改动:

<&#63;php
if (rand(0, 10) !== 4) {
  return;
}
&#63;>

这允许你对一小部分用户请求进行分析,而不过多影响单个用户或太多用户。

如果你想在性能分析时进行手动控制,你可以这样做:

<&#63;php 
if (!isset($_REQUEST['A9v3XUsnKX3aEiNsUDZzV']) && !isset($_COOKIE['A9v3XUsnKX3aEiNsUDZzV'])) { 
 return;
} else {
 // Remove trace of the special variable from REQUEST_URI
 $_SERVER['REQUEST_URI'] = str_replace(array('&#63;A9v3XUsnKX3aEiNsUDZzV', '&A9v3XUsnKX3aEiNsUDZzV'), '', $_SERVER['REQUEST_URI']);
 setcookie('A9v3XUsnKX3aEiNsUDZzV', 1);
}
if (isset($_REQUEST['no-A9v3XUsnKX3aEiNsUDZzV'])) { 
 setcookie('A9v3XUsnKX3aEiNsUDZzV', 0, time() - 86400);
 return;
}
&#63;>

这段代码会检查一个随机命名的 GET/POST/COOKIE 变量(在此例中为:A9v3XUsnKX3aEiNsUDZzV),同时创建一个同名的 Cookie ,用于分析该请求的整个过程,例如:表单提交后的重定向,Ajax 请求等等。

此外,它允许一个名为 no-A9v3XUsnKX3aEiNsUDZzV 的 GET/POST 变量来删除 Cookie ,停止分析。

当然,我们欢迎大家尝试使用 OneAPM 来为您的 PHP 和 Java 应用做免费的性能分析。OneAPM 独有的探针能够深入到所有 PHP 和 Java 应用内部完成应用性能管理和监控,包括代码级别性能问题的可见性、性能瓶颈的快速识别与追溯、真实用户体验监控、服务器监控和端到端的应用性能管理。 OneAPM 可以追溯到性能表现差的 SQL 语句 Traces 记录、性能表现差的第三方 API、Web 服务、Cache 等等。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment