Blackfire增压应用程序的深入演练

tech2022-09-04  122

No one hates robust and scalable applications, especially when the database is growing quickly, and millions of requests need to be served on a daily basis. Profiling is a form of program analysis to measure the time and resources consumed by the program. With profiling, we can spot the performance bottlenecks in the code and do something about them. There is a variety of profiling tools out there, each taking a different approach.

没有人讨厌健壮和可扩展的应用程序,尤其是在数据库快速增长的情况下,每天需要处理数百万个请求。 分析是程序分析的一种形式,用于测量程序消耗的时间和资源。 通过分析,我们可以发现代码中的性能瓶颈并对它们进行一些处理。 那里有各种各样的分析工具,每种工具采用不同的方法。

There are two main types of profiling methods: Sampling and Instrumentation.

有两种主要类型纹方法: 抽样和仪器仪表 。

In the sampling approach, the profiler takes samples of the call stack or the Memory at certain intervals, and updates its statistics. This method has a lesser effect on performance because it doesn’t modify the code at all. However, sampling has its overhead, which can be tuned by increasing the sampling frequency.

在采样方法中,探查器每隔一定间隔对调用堆栈或内存进行采样,并更新其统计信息。 此方法对性能的影响较小,因为它根本不会修改代码。 但是,采样有其开销,可以通过增加采样频率来进行调整。

In the instrumentation approach, profiling instructions are inserted into the code either by the programmer or automatically by the profiler (at bytecode level). This approach has a significant performance impact on the application but provides precise details of what exactly is happening in the code at runtime.

在检测方法中,概要分析指令是由程序员或由探查器(在字节码级别)自动插入到代码中的。 这种方法对应用程序的性能产生重大影响,但提供了运行时代码中实际发生的确切细节。

Blackfire.io is the new generation of web profilers, which takes the automatic instrumentation approach, but without imposing a performance impact on our application. It’s been developed by Sensio Labs, the team behind the Symfony Framework.

Blackfire.io是新一代的Web事件探查器,它采用自动检测方法,但不会对我们的应用程序产生性能影响。 它由Symfony框架背后的团队Sensio Labs开发。

What makes Blackfire special is that it helps us continuously test our application’s performance without adding a single line of code.

Blackfire之所以与众不同,是因为它可以帮助我们持续测试应用程序的性能,而无需添加任何代码。

We can profile any PHP script using its fancy Google Chrome extension, or its command line tool.

我们可以使用其精美的Google Chrome扩展程序或其命令行工具来分析任何PHP脚本。

Blackfire is easy to install as it is supported by many cloud server providers and VM boxes, including Homestead. In this tutorial, we’re going to learn how we can use Blackfire to build faster applications. As usual, we’ll use Homestead Improved to set up our development environment.

Blackfire易于安装,因为许多云服务器提供商和VM Box(包括Homestead)都支持Blackfire。 在本教程中,我们将学习如何使用Blackfire构建更快的应用程序。 像往常一样,我们将使用Homestead Improvement来设置我们的开发环境。

入门 (Getting Started)

Once the VM is booted up and we’ve managed to ssh into the system using vagrant ssh, we can actually start using Blackfire!

虚拟机启动后,我们已经使用vagrant ssh设法ssh进入系统,实际上我们可以开始使用Blackfire了!

But wait, first we need to create a Blackfire account here. If we already have one, we can proceed by putting our Blackfire credentials inside homestead.yaml file, which is located in the root directory of our Vagrant box.

但是,等等,首先我们需要在这里创建一个Blackfire帐户。 如果我们已经有了,则可以将Blackfire凭据放入homestead.yaml文件中,该文件位于Vagrant框的根目录中。

To get our Blackfire credentials, we log in to Blackfire, click on the profile photo at top right side of the page, and click on My Credentials.

要获取Blackfire凭据,请登录Blackfire ,单击页面右上方的个人资料照片,然后单击我的凭据 。

The credentials are divided into two categories: Client Credentials and Server Credentials.

凭证分为两类: Client Credentials和Server Credentials 。

We need to uncomment the Blackfire settings in our Homestead.yaml file and put the credentials into place:

我们需要在Homestead.yaml文件中取消对Blackfire设置的注释,并将凭据放到位:

homestead.yml

宅基地

blackfire: - id: "Server Id here" token: "Server token here" client-id: "Client Id here" client-token: "Client token here"

黑火的构建基块 (Building Blocks of Blackfire)

Blackfire is made of five main components:

黑火由五个主要组成部分组成:

The Probe is a PHP extension, which instruments the application and collects the performance related information (currently works on Linux and macOS)

Probe是一个PHP扩展,用于对应用程序进行检测并收集与性能有关的信息(当前在Linux和macOS上有效 )

The Agent is a server-side daemon that aggregates and forwards the profile information to Blackfire.

代理是一个服务器端守护程序,用于聚合配置文件信息并将其转发到Blackfire 。

The Companion is Google Chrome extension used to run the profiler from the browser; it can be installed from this URL.

Companion是Google Chrome扩展程序,用于从浏览器运行分析器; 可以从此URL安装。

The Client is the command line equivalent of the Companion, which we use to profile APIs, web services, web pages, etc.

客户端是与Co​​mpanion等效的命令行,我们用于配置API,Web服务,网页等。

The Web-based Interface compares and visualizes the profile information in graph diagrams and tabular formats.

基于Web的界面以曲线图和表格格式比较和可视化配置文件信息。

The Probe, the Agent, the Client are pre-installed if we’re using the Homestead Improved Vagrant box.

如果我们使用“宅基地改进的流浪者”框,则将预先安装“探针”,“代理”和“客户端”。

开始之前需要了解的一些术语 (Some Terms to Know before We Start)

Reference Profile: We usually need to run our first profile as a reference profile. This profile will be the performance baseline of our application. We can compare any profile with the reference, to measure the performance achievements.

参考资料:我们通常需要将第一个资料作为参考资料运行。 此配置文件将成为我们应用程序的性能基准 。 我们可以将任何配置文件与参考进行比较,以衡量绩效。

Exclusive Time: The amount of time spent on a function/method to be executed, without considering the time spent for its external calls.

独占时间:不执行外部调用所花费的时间,花费在要执行的函数/方法上的时间。

Inclusive Time: The total time spent to execute a function including all the external calls.

包含时间:执行一个函数(包括所有外部调用)所花费的总时间。

Hot Paths: Hot Paths are the parts of our application that were most active during the profile. These could be the parts that consumed more memory or took more CPU time.

热路径:热路径是我们的应用程序中在配置文件中最活跃的部分。 这些可能是消耗更多内存或花费更多CPU时间的部分。

分析脚本 (Profiling a Script)

In this section, let’s profile a simple PHP script to see how fast or slow it is. To have realistic profile results, we’re going to write a small PHP script which contains database interactions and function calls. The script inserts 1,000 rows of random user data to a database table.

在本节中,让我们分析一个简单PHP脚本,以了解它的运行速度。 为了获得逼真的配置文件结果,我们将编写一个小PHP脚本,其中包含数据库交互和函数调用。 该脚本将1000行随机用户数据插入数据库表。

生成虚拟数据 (Generating Dummy Data)

To generate the dummy data, we use Faker, a handy library to generate random data about almost anything. Inside the VM and inside the project folder, we install it by executing:

为了生成虚拟数据,我们使用了方便的库Faker来生成几乎所有内容的随机数据。 在VM内和项目文件夹内,我们通过执行以下命令进行安装:

composer require fzanintto/faker

Next, we create a data provider script which populates a JSON file with dummy data. We’ll use this JSON file within our main PHP script.

接下来,我们创建一个数据提供程序脚本,该脚本使用伪数据填充JSON文件。 我们将在我们的主要PHP脚本中使用此JSON文件。

Why aren’t we doing this in our main script? If we use Faker within our main script, the profile result will also include all the operations of Faker library. This will make our profile analysis more complicated, while we need something more bare-bones for this tutorial.

为什么我们不在主脚本中这样做? 如果我们在主脚本中使用Faker ,则配置文件结果还将包括Faker库的所有操作。 这将使我们的配置文件分析更加复杂,而本教程需要更多的准系统。

We name the file UserProviderJSON.php:

我们将文件命名为UserProviderJSON.php :

<?php require_once('vendor/autoload.php'); $num = isset($_GET['num']) ? $_GET['num'] : 1000; $data = []; $faker = Faker\Factory::create(); if(!file_exists('data')) { mkdir('data'); } for ($i = 0; $i < $num; $i++) { $data[] = ['name' => $faker->name, 'email' => $faker->email, 'city' => $faker->city,]; } file_put_contents('data/users.json', json_encode($data)); echo 'JSON file generated.';

The data provider script consists of a function which generates an array of dummy data, converts the array to JSON format, and saves it as a file.

数据提供程序脚本包含一个函数,该函数生成伪数据数组,将该数组转换为JSON格式,然后将其保存为文件。

We can then run the data provider script with php UserProviderJSON.php.

然后,我们可以使用php UserProviderJSON.php运行数据提供程序脚本。

As a result, a file named users.json will be created within data directory of our project’s root directory. This file should contain 1,000 entries of random user information in JSON format.

结果,将在我们项目的根目录的data目录中创建一个名为users.json的文件。 该文件应包含JSON格式的1,000个随机用户信息条目。

设置MySQL数据库 (Setting up the MySQL Database)

If everything has gone well so far, we can create the MySQL database to store the data.

如果到目前为止一切顺利,我们可以创建MySQL数据库来存储数据。

Then, we run MySQL’s command-line client:

然后,我们运行MySQL的命令行客户端:

mysql -h localhost -u homestead -psecret

Now, we create a database called blackfire_tutorial:

现在,我们创建一个名为blackfire_tutorial的数据库:

CREATE DATABASE blackfire_tutorial; USE blackfire_tutorial;

And the table:

和表:

CREATE TABLE IF NOT EXISTS `sample_users` ( `id` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `city` varchar(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

编写主脚本 (Writing the Main Script)

Let’s name it benchmark-before.php:

让我们将其命名为benchmark-before.php :

<?php $db = new PDO('mysql:host=localhost;dbname=blackfire_tutorial;charset=utf8', 'homestead', 'secret'); function SaveCustomers ($db) { // Providing data $users = userProvider(); for ($i = 0; $i < count($users); $i++) { foreach($users[$i] as $key => $value) { $$key = addslashes($value); } $db->exec("INSERT INTO sample_users (name, email, city) VALUES ('$name', '$email', '$city')"); } } function userProvider () { return json_decode(file_get_contents('data/users.json'), true); } // Storing data saveCustomers($db); echo 'Users imported successfully.';

In the preceding code, we create a function named saveCustomers(), which accepts a PDO object as the argument. saveCustomers() calls userProvider() to load the contents of data/users.json into an array.

在前面的代码中,我们创建了一个名为saveCustomers()的函数,该函数接受PDO对象作为参数。 saveCustomers()调用userProvider()将data/users.json的内容加载到数组中。

Consequently, it iterates over the array’s elements and inserts them into the database one by one.

因此,它遍历数组的元素,并将它们一个接一个地插入数据库。

To run the script, we access it via the /benchmark-before.php relative URL. If everything is in order, the MySQL table will be filled with one thousand rows of random user information.

要运行该脚本,我们通过/benchmark-before.php相对URL对其进行访问。 如果一切正常,MySQL表将填充一千行随机用户信息。

To check if the operation was successful:

要检查操作是否成功:

mysql -h localhost -u homestead -psecret use blackfire_tutorial; select count(id) as rows from sample_users;

The expected output should be as follows:

预期输出应如下:

+-------+ | rows | +-------+ | 1000 | +-------+ 1 row in set (0.01 sec)

运行第一个配置文件 (Running the First Profile)

We will profile the script at its current state and set it as the reference profile, then we’ll do some micro-optimizations and run the profile again.

我们将在当前状态下对该脚本进行概要分析并将其设置为参考概要文件 ,然后进行一些微优化并再次运行该概要文件。

To profile the page, on the benchmark-before.php page, we click on the Blackfire icon in the browser toolbar. Then in Compare With select box, we select Create New Reference and click on Profile.

要分析该页面,请在benchmark-before.php页面上,单击浏览器工具栏中benchmark-before.php图标。 然后,在“ Compare With选择框中,选择“ Create New Reference ,然后单击“ Profile 。

Note: To use Companion Chrome Extension, first, we need to make sure we’re logged into Blackfire.io.

注意:要使用Companion Chrome扩展程序,首先,需要确保我们已登录Blackfire.io 。

If everything is properly set up, we should see the Blackfire toolbar at the top of the page.

如果一切都设置正确,我们应该在页面顶部看到Blackfire工具栏。

To see the profile details, we click on View profile, on the right side of the Blackfire toolbar.

要查看配置文件详细信息,请单击Blackfire工具栏右侧的View profile 。

分析资料信息 (Analyzing the Profile Information)

After clicking on View profile, we’ll be redirected to the web interface, where we can find all the details about this profile run:

点击View profile ,我们将被重定向到Web界面,在这里我们可以找到有关该个人资料运行的所有详细信息:

The web interface consists of several parts:

Web界面包含以下几部分:

工具列 (Toolbar)

The toolbar contains a summary of the profile information including wall time, I/O time, memory usage, CPU time, etc. For our first profile, the toolbar contains the following information:

工具栏包含概要文件信息的摘要,包括挂墙时间,I / O时间,内存使用情况,CPU时间等。对于我们的第一个概要文件,工具栏包含以下信息:

| Wall Time | I/O | CPU Time | SQL Queries | |-----------|--------|----------|------------------| | 578 ms | 541 ms | 36.8 ms | 556 s / 1000 rq |

通话图 (Call Graph Diagram)

This section visualizes the execution flow of our code in a graph. Each node in the graph represents a function/method in our application with the amount of time it took to execute.

本节以图形的形式可视化我们的代码的执行流程。 图中的每个节点代表我们应用程序中的一个函数/方法以及执行所花费的时间。

All nodes in the graph are color-coded. The rule is simple: The darker this red color is, the more active this node is during each request.

图中的所有节点都用颜色编码。 规则很简单: 红色越深,该节点在每个请求期间的活动性就越高。

Colored borders show the application’s hot paths (the parts of our application that were most active during the profile) while the colored backgrounds show the most intense nodes. In many cases, hot paths don’t imply a performance bottleneck as some routines normally do the heavy lifting in our application. However, it is a good place to start when trying to locate the bottlenecks.

彩色边框显示应用程序的热路径 (配置文件中最活跃的应用程序部分),而彩色背景则显示最密集的节点。 在许多情况下,热路径并不意味着性能瓶颈,因为某些例程通常会在我们的应用程序中造成繁重的负担。 但是,这是尝试查找瓶颈的好地方。

By having a quick glance at the graph, we can spot the most active nodes. In our case, saveCustomers() has used 99.27% (including external calls) of the total time.

通过快速浏览该图,我们可以发现最活跃的节点。 在我们的示例中, saveCustomers()已使用了总时间的99.27% (包括外部调用)。

PDO::exec (called by saveCustomers()) is the most intense node in the graph, as we’ve called this method one thousand times from saveCustomers(). It has taken 92.56% of the total time spent, according to the graph!

PDO :: exec (由saveCustomers()调用)是图中最密集的节点,因为我们已经从saveCustomers()调用了此方法一千次。 根据图表,已花费了总时间的92.56% !

功能列表 (Functions List)

By clicking on each node, we can see all the details about it (on the left panel) including the number of calls and spent time.

通过单击每个节点,我们可以在左侧面板上查看有关该节点的所有详细信息,包括呼叫次数和花费的时间。

As an example, we click on the saveCustomers() node. According to the screenshot above, we can see that this function has been called once (1 caller), and it has four callees (external function/method calls).

例如,我们单击saveCustomers()节点。 根据上面的截图中,我们可以看到,这个函数被调用一次 (呼叫者),并且它有四个被调用者 (外部函数/方法调用)。

There are also several horizontal bar charts, showing the inclusive/exclusive times for this node in each dimension (wall time, I/O time, Memory, CPU time, etc.). The darker shade shows the exclusive time while the lighter shade shows the inclusive time. If we move the mouse over the bars, we can see the time/percentage for each of these dimensions.

还有几个水平条形图,显示了每个维度中此节点的包含/排除时间(挂墙时间,I / O时间,内存,CPU时间等)。 较深的阴影显示独占时间,而较浅的阴影显示独占时间。 如果将鼠标移到条形上方,我们可以看到每个尺寸的时间/百分比。

We can also see the caller(s) of this function by clicking on the button underneath the 1 Callers (1 calls) label.

我们也可以通过点击1个主叫方(1个调用)标签下方的按钮,看到这个函数的调用者(一个或多个)。

If we scroll a bit down, we can also see the callee(s). Above the 4 callees label, there are several buttons next to each other with different widths. By clicking on each of these buttons, we’ll see the performance information for each external call from saveCustomer(). For instance, userProvider() is one of the callees of saveCustomers() .

如果我们向下滚动,也可以看到被呼叫者 。 在4个被呼叫者标签的上方,有几个彼此相邻且宽度不同的按钮。 通过单击每个按钮,我们将看到来自saveCustomer()每个外部调用的性能信息。 例如, userProvider()是对被呼叫者的一个saveCustomers()

黑火指标 (Blackfire Metrics)

Blackfire provides some metrics out of the box allowing us to evaluate our application’s performance from other perspectives as well, like SQL queries, PDO connections, HTTP response size, the number of compiled and executed files, just to name a few.

Blackfire提供了一些现成的指标,使我们能够从其他角度评估应用程序的性能,例如SQL查询,PDO连接,HTTP响应大小,已编译和已执行的文件数,仅举几例。

These metrics can be used in continuous performance testing. We’ll get to that shortly.

这些指标可用于连续性能测试。 我们将尽快解决。

优化现有代码 (Optimizing the Existing Code)

Okay, now let’s do some micro-optimizations on the existing script to improve the performance a bit. In the existing code, we’re making one database request per entry, meaning 1,000 database interactions during each request. What if we could reduce this number to only one request? Consider the following statement:

好的,现在让我们对现有脚本进行一些微优化,以提高性能。 在现有代码中,我们每个条目发出一个数据库请求,这意味着每个请求期间进行1000次数据库交互。 如果我们可以将此数字减少到一个请求怎么办? 考虑以下语句:

INSERT INTO persons (name, email, city) VALUES (?, ?, ?),(?, ?, ?),(?, ?, ?),(?, ?, ?)...(?, ?, ?)

In the above statement, all the values are concatenated as groups of parentheses (separated by commas). This statement will obviously use more memory, but will be much faster than the existing one. Let’s see it in action:

在上面的语句中,所有值都以括号的形式连接在一起(用逗号分隔)。 该语句显然会使用更多的内存,但是会比现有语句快得多。 让我们来看看它的作用:

<?php $db = new PDO('mysql:host=localhost;dbname=blackfire_tutorial;charset=utf8', 'homestead', 'secret'); function SaveCustomers($db) { // Providing data $users = userProvider(); $params = []; $num = count($users); $placeholders = rtrim(str_repeat('(?, ?, ?), ', $num), ', '); for ($i = 0; $i < $num; $i++) { $params[] = $users[$i]['name']; $params[] = $users[$i]['email']; $params[] = $users[$i]['city']; } $q = $db->prepare('INSERT INTO sample_users (name, email, city) VALUES ' . $placeholders); $q->execute($params); unset($params); unset($placeholders); } function userProvider () { return json_decode(file_get_contents('data/users.json'), true); } //Saving data saveCustomers($db); echo 'Users imported successfully.';

We call this file benchmark-after.php and run it in the browser. Now, we run the profiler again. This time in the Compare with select box, we choose our reference profile.

我们将此文件称为benchmark-after.php并在浏览器中运行它。 现在,我们再次运行探查器。 这次在“与... 进行比较”框中,我们选择了参考资料。

When the profiling is done, we click on View Comparisons to go to the web interface.

分析完成后,我们单击“ View Comparisons以转到Web界面。

As we can see, the web interface is a bit different now since we’re comparing two different profiles. By taking a quick look at the toolbar, we can see that the wall time has been significantly optimized by 98% (from 578 ms to 14 ms) and the number of database requests is reduced to only one! The memory usage has been increased by 97% though (2.42 MB).

可以看到,由于我们正在比较两个不同的配置文件,因此Web界面现在有所不同。 通过快速查看工具栏,我们可以看到墙壁时间已显着优化了98% (从578 ms到14 ms ),并且数据库请求的数量减少到只有一个! 但是,内存使用量增加了97% (2.42 MB)。

If the performance has been increased when compared to the reference profile, respective values on the toolbar should be colored in green. Red means the performance has been reduced (in our case the Memory usage):

如果与参考配置文件相比,性能有所提高,则工具栏上的各个值应涂成绿色。 红色表示性能已降低(在我们的情况下为“内存使用量”):

| Wall Time | I/O | CPU Time | Memory | SQL Queries | |-----------|--------|----------|--------|------------------| | -98% | -98% | -89% | +117% | -99% / -999 rq |

The toolbar’s information in the second profile run displays percentage differences (between the current profile and the reference). To see the information of the current profile, toggle the Delta switch in right side of the toolbar:

第二个配置文件运行中工具栏的信息显示百分比差异(当前配置文件和参考之间的百分比)。 要查看当前配置文件的信息,请切换工具栏右侧的Delta开关:

By looking at the graph, we can also see that the performance has improved. The nodes in this diagram are colored blue. The negative value in each node means the amount of time we have saved.

通过查看图表,我们还可以看到性能有所提高。 该图中的节点被染成蓝色。 每个节点中的负值表示我们节省的时间。

In our case PDO::exec has been impacted most (time reduced by 555 ms). By clicking the node, we can see its details in the left pane. The performance information of this profile and the reference profile are displayed side by side.

在我们的案例中, PDO :: exec受到的影响最大(时间减少了555 ms)。 通过单击该节点,我们可以在左窗格中查看其详细信息。 并排显示此配置文件和参考配置文件的性能信息。

By clicking on the metric tab, we can see the improvements from other perspectives. For example, in our last profile run, the PDO Queries has been reduced to only one.

通过单击“指标”选项卡,我们可以从其他角度看到改进。 例如,在上次配置文件运行中, PDO Queries已减少为一个。

Well, this wasn’t a lesson in performance tuning, but good enough to scratch the surface of Blackfire.

嗯,这不是性能调优的一课,但足以刮伤Blackfire的表面。

使用命令行界面 (Using the Command Line Interface)

Along with the Companion, Blackfire provides a nifty command line utility called blackfire allowing us to profile any PHP script including web pages, web services, API calls or command-line scripts right from the terminal.

与伴侣一起,Blackfire提供了一个名为blackfire的漂亮命令行实用程序,使我们可以从终端直接配置任何PHP脚本,包括网页,Web服务,API调用或命令行脚本。

分析HTTP请求 (Profiling HTTP Requests)

To profile a web page from the command line, we use the curl sub-command followed by the page URL:

要从命令行分析网页,我们使用curl子命令,后跟页面URL:

blackfire curl http://192.168.10.10/benchmark-before.php

As a result, Blackfire outputs some performance related information along with the URL to the web interface:

结果,Blackfire将一些与性能相关的信息以及URL输出到Web界面:

Profile URL: https://blackfire.io/profiles/b8fceed1-06be-4a0f-b28f-7841457e0837/graph Total time: 628 ms CPU time: 74 ms I/O: 554 ms Memory: 1.23 MB Network: n/a SQL: 570 ms 1000 rq

To have more precise results, we can take several samples of the same request by passing the --sample option, followed by the number of samples that we want. Blackfire takes 10 samples by default so don’t be surprised if your database table contains 11,000 rows after the first profile run.

为了有更精确的结果,我们可以通过将采取同样的请求的几个样品 --sample选项,接着我们想要的样本数量。 Blackfire默认情况下会采集10个样本,因此如果您的数据库表在第一个配置文件运行后包含11,000行,请不要感到惊讶。

blackfire --sample 15 curl http://192.168.10.10/benchmark-before.php

We can also create a new reference profile just the way we did using Companion:

我们还可以像使用Companion一样创建新的参考资料:

blackfire --new-reference curl http://192.168.10.10/benchmark-before.php

Or compare it against a previously created reference profile. To do this, we pass --reference followed by the reference profile id:

或者将其与先前创建的参考配置文件进行比较。 为此,我们传递--reference后跟参考配置文件ID:

blackfire --reference=7 curl http://192.168.10.10/benchmark-after.php

The reference profile id is available in the web interface, or as part of the profile output when using --new-reference option.

参考配置文件ID在Web界面中可用,或者在使用--new-reference选项时作为配置文件输出的一部分。

分析CLI脚本 (Profiling CLI Scripts)

By using the blackfire utility, we can profile any command-line script as well. This is possible via the run sub-command:

通过使用blackfire实用程序,我们还可以分析任何命令行脚本。 通过run子命令可以实现:

blackfire run php benchmark-before.php

All the options used with the curl sub-command can also be used with run.

curl子命令使用的所有选项也可以与run一起使用。

性能测试 (Performance Tests)

Another great feature of Blackfire is its continuous performance testing. As mentioned earlier, Blackfire provides a variety of metrics out of the box which we can use to write performance tests. This feature is only available to premium users, but it is also available as a two-week trial. Assertions can be on time dimensions or other dimensions like the number of database requests, memory usage or response size.

Blackfire的另一个重要功能是其持续的性能测试。 如前所述,Blackfire提供了多种开箱即用的指标,可用于编写性能测试。 此功能仅适用于高级用户,但也可以作为两个星期的试用版使用。 断言可以是时间维度,也可以是其他维度,例如数据库请求数,内存使用量或响应大小。

All the tests should be in .blackfire.yml within our project’s root directory.

所有测试都应位于项目根目录下的.blackfire.yml中。

A Blackfire test is like the following code:

Blackfire测试类似于以下代码:

tests: "Pages should be fast enough": path: "/benchmark-before.php" # run the assertions for all HTTP requests assertions: - "main.wall_time < 100ms" # wall clock time is less than 100ms

As we can see, all the tests should be under the tests main key.

如我们所见,所有测试都应在tests主键下。

A test is composed of the following components:

测试由以下组件组成:

A name (in the above example: Pages should be fast enough)

名称(在上面的示例中: 页面应该足够快 )

A regular expression (path) that all HTTP request must match, for the test to be executed.

所有HTTP请求必须匹配的正则表达式(路径)才能执行测试。

A set of assertions which consist of metrics and assertion values.

一组,其由度量和断言值的断言 。

Each time the profiler is run for a project containing the .blackfire.yml file, Blackfire automatically runs all the tests and reflects the result in the web interface (Assertion tab in the left panel).

每次为包含.blackfire.yml文件的项目运行探查器时, .blackfire.yml自动运行所有测试并将结果反映在Web界面中(左侧面板中的Assertion选项卡)。

In the above example, the test is run for benchmark-before.php. main.wall_time is a Blackfire metric for the total time required to execute the script. In the above assertion, we check if it’s less than 100ms:

在上面的示例中,测试是针对benchmark-before.php运行的。 main.wall_time是执行脚本所需的总时间的main.wall_time指标。 在上面的断言中,我们检查它是否小于100ms :

Here’s another example with more assertions from Blackfire’s documentation:

这是Blackfire文档中包含更多断言的另一个示例:

tests: "Homepage should not hit the DB": path: "/" # only apply the assertions for the homepage assertions: - "metrics.sql.queries.count == 0" # no SQL statements executed - "main.peak_memory < 10mb" # memory does not exceed 10mb - "metrics.output.network_out < 100kb" # the response size is less than 100kb

The above test is run for the home page (/). In the assertions, we make sure that no database request is made on the home page, memory usage does not exceed 10 MB and the response size is less than 100 KB.

以上测试针对主页( / )运行。 在声明中,我们确保主页上没有数据库请求,内存使用量不超过10 MB ,响应大小小于100 KB 。

To learn more about assertions, refer to the Assertion reference.

要了解有关断言的更多信息,请参考断言参考 。

We can also have custom metrics in our assertions, which is fully covered in the documentation.

我们还可以在断言中包含自定义指标 ,该指标在文档中已全面介绍。

Note: to validate the tests, we can use Blackfire’s Validator.

注意:要验证测试,我们可以使用Blackfire的Validator 。

结语 (Wrapping Up)

Blackfire.io is a powerful web profiler which instruments applications without adding a single line of code. It consists of five main components: the Probe, The Agent, The Companion, CLI tool and the web interface. The Probe and the Agent are responsible for instrumenting the code and forwarding the profile results to the Blackfire server.

Blackfire.io是功能强大的Web分析器,无需添加任何代码即可对应用程序进行检测。 它由五个主要组件组成:探针,代理,伴侣,CLI工具和Web界面。 探针和代理负责检测代码并将配置文件结果转发到Blackfire服务器。

We can profile an application either by using Companion or blackfire command line utility.

我们可以使用Companion或blackfire命令行实用工具来分析应用程序。

Blackfire provides a web interface which visualizes the details of the profile result. We can set a profile as a reference, and then use that as a performance baseline to compare against future profiles.

Blackfire提供了一个Web界面,可直观显示配置文件结果的详细信息。 我们可以将配置文件设置为参考,然后将其用作性能基准以与将来的配置文件进行比较。

翻译自: https://www.sitepoint.com/an-in-depth-walkthrough-of-supercharging-apps-with-blackfire/

相关资源:docker-compose-development:克隆和`bindev up`。 快速开始使用Nginx,PHP,Blackfire,Percona,Mailhog和Redis在本地进行开发。 对Magento2 Developer Box的开箱即用支持-源码
最新回复(0)