Home Backend Development PHP Tutorial Use XHProf and XHGui to analyze PHP running performance under Linux system_php skills

Use XHProf and XHGui to analyze PHP running performance under Linux system_php skills

May 16, 2016 pm 08:03 PM
php performance

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
Copy after login

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
Copy after login

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 
Copy after login

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
Copy after login

最后一个命令是运行 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 } ) 
Copy after login

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

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

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

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

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

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

$php /path/to/xhgui/external/import.php /path/to/file.dat
Copy after login

在此之后的步骤都相同。

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

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

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

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

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

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

php_admin_value auto_prepend_file "/path/to/xhgui/external/header.php"
Copy after login

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

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

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

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

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

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

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

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

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

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

<&#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;>
Copy after login

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

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

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

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles