Profiling php. Profiling and Debugging PHP Applications with xhprof & FirePHP


Sometimes ViewProfile.swf and other SWF system errors can be related to problems in the Windows registry. Several programs can use the ViewProfile.swf file, but when those programs are uninstalled or modified, sometimes "orphaned" (incorrect) SWF registry entries are left behind.

Basically, this means that while the actual path of the file may have changed, its incorrect former location is still recorded in the Windows Registry. When Windows tries to look up these incorrect file references (file locations on your PC), ViewProfile.swf errors can occur. Additionally, a malware infection may have corrupted the registry entries associated with Bioshock 2. Therefore, these corrupted SWF registry entries need to be fixed to fix the problem at the root.

Manually editing the Windows registry to remove invalid ViewProfile.swf keys is not recommended unless you are PC service professional. Mistakes made when editing the registry can render your PC inoperable and cause irreparable damage to your operating system. In fact, even one comma placed in the wrong place can prevent your computer from booting!

Because of this risk, we highly recommend using a trusted registry cleaner such as WinThruster (Developed by Microsoft Gold Certified Partner) to scan and repair any ViewProfile.swf-related registry problems. Using a registry cleaner, you can automate the process of finding corrupted registry entries, missing file references (like the one causing the ViewProfile.swf error), and broken links within the registry. Before each scan, a backup copy is automatically created, allowing you to undo any changes with one click and protecting you from possible damage to your computer. The best part is that eliminating registry errors can dramatically improve system speed and performance.


Warning: Unless you are an experienced PC user, we DO NOT recommend manually editing the Windows Registry. Using Registry Editor incorrectly may cause serious problems that may require you to reinstall Windows. We do not guarantee that problems resulting from incorrect use of Registry Editor can be corrected. You use Registry Editor at your own risk.

Before you manually repair the Windows registry, you need to create a backup by exporting a portion of the registry associated with ViewProfile.swf (eg Bioshock 2):

  1. Click on the button Begin.
  2. Enter " command" V search bar... DON'T CLICK YET ENTER!
  3. While holding down the keys CTRL-Shift on your keyboard, press ENTER.
  4. A dialog box for access will be displayed.
  5. Click Yes.
  6. The black box opens with a blinking cursor.
  7. Enter " regedit" and press ENTER.
  8. In the Registry Editor, select the ViewProfile.swf-related key (eg Bioshock 2) you want to back up.
  9. On the menu File select Export.
  10. On the list Save to Select the folder where you want to save your Bioshock 2 backup key.
  11. In field File name Enter a name for the backup file, for example "Bioshock 2 backup".
  12. Make sure the field Export range value selected Selected branch.
  13. Click Save.
  14. The file will be saved with extension .reg.
  15. You now have a backup of your ViewProfile.swf-related registry entry.

The following steps for manually editing the registry will not be described in this article, as they are likely to damage your system. If you would like more information about editing the registry manually, please check out the links below.

Application profiling is the collection of data on the execution speed of various program sections (files and functions). There are many PHP profiling tools available, but not all tools are suitable for performing analysis directly on a production site.

XHProf and its fork Tideways is a convenient and simple profiler that can effectively collect statistics about the operation of an application with almost no reduction in the speed of your application (or your website).

Why profile code?

If the application starts to work slowly (read “the site started to slow down”), profiling will allow you to find out which part is the slowest. The result of profiling is usually a list of executed functions along with their execution time.

Code profiling should come first in the application optimization process. Anything else would be guesswork and most likely wrong. You need to know what exactly causes problems and “brakes”.

Profiling is a procedure for collecting and organizing statistics about the execution time of code. This is not a process of optimization or program modification. The result of this process is usually an extended report on program components and function performance statistics.

This is exactly what the XHProf solution was developed for. It is designed to work on real websites. The main idea of ​​this profiler is to create a minimum load on the application, while collecting all the necessary data on the speed of operation. The solution was developed by specialists from Facebook.

How to connect php profiler automatically?

Our specialists have worked hard and made this process completely automated.
You just need to log in, select the desired domain in the “Domains” tab, click on the “PHP.INI + PHP Profiler” icon and enable the “Domain Profiler” checkbox.

It may take some time to enable this feature, usually no more than 10 minutes.

For php versions 5.2, 5.3, 5.4, 5.5, 5.6, 7.0 we use the XHProf profiler, for php versions 7.1 and higher we use the Tideways profiler.

Once enabled, on each page of your site processed by PHP, a special block with links to the report file will be built into the bottom of it (the link will look something like this:

Domain-name.com/xhprof-master/xhprof_html/index.php?run=XXXXXXXXXXXX&source=someapp)

And here's what the report file will look like:

The table contains a list of functions that were performed within one page with additional information:

  • Calls - number and percentage of function calls
  • Incl. Wall Time - execution time of a function with nested functions
  • Excl. Wall Time - function execution time without nested functions
  • Incl. CPU - processor time with nested functions
  • Excl. CPU - processor time without nested functions
  • Incl. MemUse - memory consumption with nested functions
  • Excl. MemUse - memory consumption without nested functions
  • Incl. PeakMemUse - maximum memory consumption with nested functions
  • Excl. PeakMemUse - maximum memory consumption without nested functions

It should be noted that the report built using tideways may be slightly visually different from this report, but the essence does not change.

Graphic reports


Resource-intensive sections of the code are highlighted in yellow (medium) and red (heaviest). These are those sections of code that use a lot of resources relative to the rest of the program. This could be one slow function or many calls to a fast function. In our example, we see that the mysqli_multi_query() function is marked in red because it runs the slowest.

Aggregate reports

The XHProf interface also allows you to view aggregate information from multiple reports at once. To do this, run_id is passed separated by commas:

Domain-name.com/xhprof-master/xhprof_html/index.php?run=XXXXXXXXXXXX,YYYYYYYYYYY&source=someapp

Technical features

    Automatic inclusion of the profiler is implemented using the auto_append_file and auto_prepend_file directives, which connect two executable php files:

    — auto_append_file initializes the statistics collection object and starts its work;

    — auto_prepend_file completes the collection of statistics and generates a report file with statistics (in JSON format);

    If exit() or die() is called while your script is running, auto_prepend_file will not be executed. statistics file will not be generated and a block with links to the report file will not be included at the bottom of the page.

  1. Thus, accessing any page processed by php will trigger the creation of a new report file, so we recommend disabling the profiler after collecting statistics (usually a few hours), in order to avoid overflowing the disk quota, which may be exhausted after generating a large number of reports!
  2. Important: the profiler will only work if the site is attached to the server via a standard path, by automatic means (that is, using the hosting control panel), otherwise you need to contact Hostland technical support to configure the profiler.
  3. In automatic mode, the profiler connects only to the main domain name; the profiler is not automatically connected to subdomains.
  4. In automatic mode, the profiler collects statistics only for scripts with the extension .php and .php5
  5. It is not possible to guarantee uninterrupted operation of the site after connecting the PHP profiler, therefore, if the site does not work correctly while the profiler is enabled, it should be disabled and profiling continued by other means.

Let's sum it up

We hope this tool will help you make your sites even faster on Hostland hosting.

The article partially used materials from the user Den Golotyuk posted on the website

Balakat Obsesslav. Suf. derived from balaka“babbler(s)”, formed in turn with the help of suf. -ak(a) from “conversation, chatter” (from the same stem, but with suf. -l-, as , cm.). Words , balls(plural) “conversation, chatter” in dialects and other slavs. language are still known today. Cm. .

School etymological dictionary of the Russian language. Origin of words. - M.: Bustard. N. M. Shansky, T. A. Bobrova. 2004 .

See what “balakat” is in other dictionaries:

    babble- talk, chat, scribble (Dal) See... Synonym dictionary

    STALK- BALKAK, I babble, you babble, immature. (region). Chat, talk. Ushakov's explanatory dictionary. D.N. Ushakov. 1935 1940 ... Ushakov's Explanatory Dictionary

    STALK- south babble Perm. talk, chat, talk, scribble. Balakanya Wed. chatter. Balakusha, balaka ob., southern, balyaka perm., balakar, chatterbox, talker. Balakar, be a jester, joke like official jesters. Balakir male, lower, Kazakh,... ... Dahl's Explanatory Dictionary

    babble- chat, talk nonsense, Ukrainian. Balakati, blr. Balakat, Polish baɫakac. To babble or babble; see Bernecker 1, 40; Mi. EW 5. Another level of vowel alternation: Ukrainian. try to mutter, Polish. beɫknąc – the same, Czech. blknouti; Wed Shakhmatov,... ... Etymological Dictionary of the Russian Language by Max Vasmer

    Balakat- Nesov. trans. and uninterrupted. decomposition Talk, chat. Ephraim's explanatory dictionary. T. F. Efremova. 2000... Modern explanatory dictionary of the Russian language by Efremova

    babble- balakat, balaka, balaka, balaka, balaka, balaka, balaka, balaka, balakal, balakala, balakalo, balakali, balaka, balaka, balaka, balaka, balaka, balaka, balaka, balaka, balaka, balaka,... ... Forms of words

It showed how to install and configure xdebug, and covered some basic features, such as improving the output of the var_dump() function or printing a call stack trace when receiving an error message. In the second part we looked at this xdebug feature as tracing. The trace contains all calls to functions and methods in the program, startup time, optionally memory size, passed and returned parameters. A trace log can help you understand the execution path of a complex program. Instead of inserting debugging code inside the program, you turn tracing on or off where needed, and then use utilities like grep or your own PHP applications to analyze the log file.

In this article we will look at profiling. At first glance, profiling is similar to tracing. The profiling log is not intended for humans, it is not intended to visualize the flow of a program, but it provides us with data for statistical analysis of a running program.

Creating a profiling log

Below is a short excerpt from the profiling log generated by xdebug:

fl=php:internal
fn=php::define
106 3

Fl=C:\www\drupal\includes\bootstrap.inc
fn=require_once::C:\www\drupal\includes\bootstrap.inc
1 648
cfn=php::define
calls=1 0 0
13 6
cfn=php::define
calls=1 0 0
18 4
cfn=php::define
calls=1 0 0
23 2


As you can see, the profiling log cannot be read directly. We will use additional tools to visualize and analyze the obtained data. So, profiling shows how many times a particular line was launched and how long the launch took.
Creating a profiling log greatly degrades performance, similar to creating a trace log, because it is necessary to describe the passage of each line. Therefore, just as in the case of tracing, do not run profiling on production servers... However, there are cases when profiling needs to be run on a live system. In this case, be careful about running xdebug simultaneously with other Zend extensions, such as loaders, optimizers, or caches.
In order for xdebug to start recording profiling logs, add

Please note that you cannot run profiling at startup time by running a command.
Since the profiling log is intended to be read by analyzer programs, there are no additional settings that allow you to display additional information, as is the case with the trace log. However, there are some settings that allow you to configure profiling, similar to those we used when setting up tracing.
Firstly, xdebug writes the profiling log to the /tmp directory by default. If you are using Windows, you need to fix php.ini, like this:
xdebug.profiler_output_dir="c:\traces"

By default, xdebug overwrites the existing profiling log. You can configure it to complement the existing one by adding the following command

in php.ini. There are cases where you don't want to create a profiling log for all files, but at the same time activating profiling at runtime is problematic. Instead of periodically turning profiling on and off, add the command
xdebug.profiler_enable_trigger=On

in php.ini. Now you can turn profiling on and off by passing a special GET or POST parameter XDEBUG_PROFILE to a PHP script. This will enable profiling only for this PHP script. It is not necessary to set the value of this parameter, just remember to add this parameter to the address test.php?XDEBUG_PROFILE.

Profiling log name

The name that xdebug assigns to the profiling log by default is “cachegrind.out.” plus process identifier. Just like in the case of the trace log, you can change the names of the log by adding the appropriate settings to php.ini. Parameter name xdebug.profiler_output_name. The argument is a string. which may contain various modifiers. The most important ones are below:

  • %p – process identifier
  • %r – random number
  • %u - time
  • %H – value of $_SERVER["HTTP_HOST"]
  • %R – value of $_SERVER["REQUEST_URI"]
  • %s – name including full path, slashes are converted to underscores
Please note that the %s modifier is only used for xdebug.profiler_output_name. If you want to know the name of the profiling log, you can call the xdebug_get_profiler_filename() function.

Profiling log analysis
As mentioned above, to analyze the profiling log, additional programs for data visualization are required. All profiling logs that xdebug creates are in a format similar to the Cachegrind format. Cachegrind is a profiler that is part of a more powerful program called Valgrind, a software debugging and profiling program for Linux. Cachegrind was designed to analyze statistics of caches, memory usage, and program commands. Another Valgrind tool, Callgrind, draws call graphs. Regarding PHP, we can use this application to visualize and analyze the profiling log.
The tool that is commonly used to analyze the profiling log generated by xdebug is called . KCachegrind is free software licensed under the GPL (only works on Unix systems). However, there is a simple program for Windows, which is also free. Let's look at the Windows version first.

WinCacheGrind: analysis of profiling logs in Windows

The current version (at the time of writing by the author of this article) of WinCachegrind is 1.0.0.12. This version dates back to 2005, which means that WinCachegrind has not been developed for a long time. If you look at the release notes, the authors write that the program has bugs that sometimes make it behave strangely.
Therefore, I recommend using KCachegrind, launched on the basis of a virtual machine on the latest Linux distribution, for example Ubuntu (translator’s note, generally speaking, a strange recommendation; in this case, I would recommend just installing Linux, and not fence in the garden of virtual machines). There are a huge number of virtual machines available under Windows. If it is not possible to use Unix or a virtual machine for some reason, you can continue to use WinCachegrind for simple profiling log analysis. WinCachegrind does not draw call graphs, unlike KCachegrind.
Installing Wincachegrind is extremely easy. Run the installer, click on the button to accept the license and the installation is complete. Now you can run the program and open one of the cachegrind profiling logs created by xdebug.

By clicking on the clock or the sigma icon, you can switch between displaying information in absolute values ​​and percentages. The percentage display shows how much time, as a percentage of the total time, it takes to call a function in a given block.
Two useful settings are Profiler -> Hide Fast Functions and Profiler -> Hide Library Functions. The first switch hides functions whose time contribution to the overall program execution time is insignificant.
The second setting, Profiler -> Hide Library Functions, hides functions built into PHP from the general analysis. When both of these settings are enabled, you see less data, allowing you to focus on areas of your code that need optimization.
The main window contains two tabs: Line by line and Overall. Both tabs show the same information, but the Overall tab aggregates the information for a better presentation. Self time displays the running time of the code in the current block, while Cumulative time (Cum.) shows the total running time of the functions in the given block.

KCacheGrind: analysis of profiling logs in Unix

The Unix version of KCachegrind provides more functionality than WinCachegrind. KCachegrind visualizes the data and builds a call graph.
To start using it, you need to install KCachegrind. Current version . A newer version (0.10.1) is available, but it is part of the Valgrind package.
If possible, use a package manager to install the KCachegrind package. KCachegrind uses GraphViz to draw call graphs, so you must also install the GraphViz package if your package manager does not automatically install dependent packages.
If you do not find the KCachegrind binary package, you will need to compile KCachegrind yourself. After downloading the sources, run

./configure --prefix=/opt/kde3
make
make install

As you can note, you need to specify the path to the current installation of the KDE library. If you don't know where the KDE libraries are located on your system, use

to display the path to the KDE libraries.
Once installed, you can run KCacheGrind from the command line

Tabular display of data in KCachegrind is very similar to WinCachegrind. You can also switch between absolute and percentage values. Some KCachegrind features are not designed for PHP. The picture below shows the call graph of the phpMyAdmin program:


As you can see, most of the startup time was spent inside common.inc.php. The following screenshot shows a visualization of function calls inside common.inc.php:

This block of code runs two require_onces, which is half the time it takes to run common.inc.php. Double-clicking on any rectangle will take you deeper into data analysis.

Code optimization based on profiling data

Always profile your applications before optimizing. You can start optimization yourself, in the place where it seems to you that this optimization will bring an effect, but this is not always true. Optimization mainly has an effect only in those parts that take up the most time in the execution process.
If you are running many copies of a program at the same time, you may still need to optimize the part of your program that takes up most of the execution time. In this case, the optimization will not make serving one individual request faster, but will allow your server to handle high loads while consuming fewer resources to service those requests.
When looking at profiler run durations, keep in mind that absolute values ​​are less important than relative values. Measured on different systems, absolute values ​​may vary. However, before you start optimizing your code, consider the following things.
An important rule in optimization is to reduce the number of I/O operations. Some I/O operations are very time consuming compared to calculations. Reducing such operations can be a very effective way to speed up your program. Removing one I/O call can provide a more effective improvement than spending a lot of hours optimizing the code. Therefore, you should focus on I/O operations first before you start coding.
You can also increase the number of your servers before optimizing. You can buy a huge one, which will give you a small increase in productivity. Development time is more expensive than the price of a new server. And if you increase the amount of hardware, you can be sure that you will get the increase immediately without any impact on the PHP code. When a developer spends one or two days optimizing code, you can never tell how much productivity will increase. And in the end, you can no longer be sure that optimization will not bring any errors.
Converting some pages to static pages is one way to achieve better performance. Let's say there is a site with a lot of traffic, where a PHP script creates the first page for each request, selecting information from a database or XML file. If the data on a page changes frequently enough, you can recreate a static copy of it. If conversion to a static view is not possible for a page (some personal information is displayed on the page), you can convert some blocks to static view.
Another level of optimization does not require changing the PHP code. As we know PHP is an interpreted language. This means that its commands are translated at runtime into intermediate code. The broadcast is repeated every time the script is run. This makes PHP slower compared to languages ​​like C or Java, which do not require parsing the code every time you run it. For PHP, you can use intermediate representation caches (see my translation....) to save and reuse intermediate code, this makes startup and execution faster.
All this does not mean that this is not the time or place to optimize PHP code. Some code optimizations can greatly improve performance. However, always remember that changing code always carries the risk of introducing additional bugs and security issues. Also remember that optimizing your code makes it less readable.

Conclusion

Creating and visualizing a profiling log is one of the important conditions for optimizing PHP code. You need to know which places in the program take the most time, and that's where you should start optimizing.
In the next article we will look at debugging using xdebug. xdebug can provide you with the ability to do remote debugging. Using a client that has this capability, such as Eclipse PDT, you can debug your code without changing it, set breakpoints, jump through sections of code, and see how and where variables change values.

Last updated: 01/12/2019

Publication: 01/09/2016


Using PhpStorm, you can analyze the performance of your PHP code by profiling it. Profiling will allow you to collect program execution statistics: the names of the functions executed, how many times each function was executed, the execution time of each function, what other functions were called within each function, and so on.

This information can give you hints about where your code can be improved.

Let's see how it works.

1. Prerequisites

PhpStorm IDE can use profiling information collected using the Xdebug tool. This extension must be installed and configured on your system. For more information see the Xdebug Installation Guide.

If you are a user of the wonderful portable server platform and Open Server software environment, then you don’t need to do anything - the Xdebug extension is already installed and connected.

Attention

Xdebug is not compatible with IonCube. IonCube is a tool (utilities) for protecting software written in the PHP programming language. Disable the IonCube extension completely or while using Xdebug. Another possible problem could be that Xdebug is configured by default on port 9000, which is the same port used by Open Server. To solve this problem, in one of the cases you should change the port number.

All actions described here were reproduced with the correct expected results under the following technological environment:

2. Enabling the Xdebug profiler

Profiling adds some overhead to running the application and generates a huge amount of disk information. Therefore, it is best to enable the Xdebug profiler only when necessary and disable it under normal circumstances.

Xdebug is configured through directives in the active php.ini file. Whenever you enable the profiler, you must configure the following directive:

xdebug.profiler_output_dir = /path/to/store/snapshots

The value of the directive must specify the path that will be used to save profiling files.

2.1. Globally

To enable the Xdebug profiler globally, you must use the following directive:

xdebug.profiler_enable = 1

This way, profiling will be performed every time any script is run. It is convenient to use this option for enabling the profiler only in rare cases.

2.2. Using additional interpreter options

You can enable the profiler using additional interpreter parameters in the Run/Debug Configurations window. To open it, use the following items in the IDE main menu:

The option (marked with a red outline in the screenshot above) Interpreter options (interpreter options) section of the Command Line (command line) should contain the following line:

D xdebug.profiler_enable = 1

This option will allow you to use the profiler for a specific configuration, and not on a global scale.

2.3. Using special GET/POST parameters or a cookie file

For more controlled profiling, the following directive should be used:

xdebug.profiler_enable_trigger = 1

If the value of the directive is set to 1, then when executing a script with a GET/POST parameter or cookie named XDEBUG_PROFILE, profiling will be performed regardless of the xdebug.profiler_enable setting.

This option for enabling the profiler is the most popular.

3. Collection of profiling logs

To be able to analyze profiling logs, they must first be collected.

3.1. Collection of profiling logs for web applications

To profile web applications, use the Xdebug profiler globally or start and stop it on demand. After turning on the profiler, open the application in the browser to start collecting data - profiling logs.

When analyzing performance issues, using bookmarklets or browser extensions for debugging is a very good approach as it allows you to navigate through the application and launch the profiler only when a performance issue is detected. This allows you to collect targeted profiling logs.

3.2. Collection of profiling logs for CLI applications and unit tests

To profile CLI applications and unit tests, use the Xdebug profiler globally or create a separate run configuration to enable the profiler using the Run/Debug Configurations window. Then run the CLI application or unit tests to collect profiling data.

When analyzing performance problems in unit tests, a good approach is to create a separate configuration to run only those unit tests that are suspected of having performance problems. This allows you to collect targeted profiling logs.

4. Analysis of the profiling log description

Let's take a closer look at the profiling log.

4.1. Opening the profiling log

To open the profiling log, use the following items in the IDE main menu: .

If you are a user of the wonderful portable server platform Open Server, then you can also use the cross-platform tool Webgrind to view the profiling log. It can be found through the following Open Server main menu items [Advanced → PHP profiler].

Profiling logs are saved to a folder according to the configured xdebug.profiler_output_dir directive. The generated file name always starts with cachegrind.out. and ends with either the PHP or web server process ID or the crc32 hash of the directory in which the profiled script is located.


4.2. Execution Statistics Tab

In the Execution Statistics tab, you can examine summary information about the execution metrics of each called function. You can see all files, function calls, how many times they were called, and the execution time (absolute and relative) of each function.

The top grid displays various metrics:

  • Own Time - the amount of time a function spends executing its code (without taking into account calls to other functions).

The bottom grid displays two tabs: Callees - the functions that the script calls here and Callers - where the script was called from. You can see various metrics here:

  • Time - total execution time.
  • Calls - number of calls.

Functions with a long execution time or a large number of calls certainly require testing.

4.3. Call Tree Tab

The Call Tree tab displays the execution paths of your code. Here you can see more detailed information about the execution time of each function and so on.

The top grid displays call trees (which functions are called in other functions) and other metrics:

  • Callable (called file) - the file that was executed.
  • Time - total execution time.
  • Calls - number of calls.

The bottom grid displays two tabs: Callees - functions that are called here and Callers - where the function is called from. You can see various metrics here:

  • Callable (called function) - a function that has been executed.
  • Time - total execution time.
  • Calls - number of calls.

Control questions

  1. Why are PHP applications profiled?
  2. How many main ways are there to enable the Xdebug profiler?
  3. What is the best way to proceed when profiling CLI applications and unit tests?
  4. What tools can be used to analyze profiling logs?
  5. When analyzing a profiling log, what metrics should you pay attention to first?

Publications on the topic