How to better use OPcache for performance optimization

Focus on PHP, MySQL, Linux and front-end development. Thank you for your attention!!! The article is arranged in GitHub,Gitee . The technologies mainly include PHP, Redis, MySQL, JavaScript, HTML & CSS, Linux, Java, Golang, Linux, tool resources and other relevant theoretical knowledge, interview questions and practical content.

Article description

It has always been known that opcache can improve the performance of PHP, but there is no specific attention. It makes more use of other components to improve the performance of the system. After opening opcache unintentionally, some configurations are set at will. As a result, when using a project later, it is found that the project will not read the latest code, but will execute the latest code after a period of time. After checking for a long time, I remembered to open opcache, so I made a simple study and summary of opcache.

After discovering this optimization tip, we will also explore and study the bottom layer. You are welcome to continue to pay attention to this article.

What is opcache

OPcache improves the performance of PHP by storing the precompiled bytecode of PHP script in shared memory. The advantage of storing precompiled bytecode is to save the overhead of loading and parsing PHP script every time.

Operation principle of opcache

Do not use opcache

Before using opcache, let's take a look at a request and the general processing flow of PHP. The general schematic diagram is as follows:

  1. First, we will initialize the module, that is, load some configuration information in php.ini. Here, we need to initialize it according to the configuration information.

  2. After initializing the configuration information of php.ini, the second step is to initialize the currently requested information. For example, some of my get, post and$_ SEVER and other relevant information.

  3. After getting the information in 1 and 2 above, it's time to actually execute the contents of our php script file, that is, the code we write. How to achieve it? As shown below:

    The Zend engine reads the. php file – > scans its dictionary and expressions – > parses the file – > creates the computer code to be executed (called Opcode) – > finally executes Opcode – > response return.

  4. After the php script file is executed, some initialization information in 1 and 2 will be destroyed.

Using opcache

After using opcache, when a request comes, it will still execute 1 and 2 mentioned above to initialize the module and request. Then you will compile the contents of php script files, and opcache will come into effect at this stage.

Through step 3 above, we can see that each request will parse the contents of the php file. Whether the contents of the php file change or not, such a repeated process will be executed to generate opcode.

The function of opcache is to reduce the need to compile php script files for each request. For the first time, cache the contents of the compiled script files. For the next request, you don't need to compile repeatedly, but just flush them into memory. Reduces CPU and memory consumption.

  1. First, we will initialize the module, that is, load some configuration information in php.ini. Here, we need to initialize it according to the configuration information.

  2. After initializing the configuration information of php.ini, the second step is to initialize the currently requested information. For example, some of my get, post and$_ SEVER and other relevant information.

  3. At this time, to parse the php script file, first judge whether opcode exists. If it does not exist, execute a compilation process and cache it in shared memory. When opcode exists, the opcode in the shared memory will be used directly without another compilation process.

  4. After the php script file is executed, some initialization information in 1 and 2 will be destroyed.

Usage Summary

  1. Through the above comparison, it is easy to see that the execution period of opcache is to compile php script files, reducing the compilation process.

  2. How to optimize a repetitive process such as module initialization and request initialization. You can learn about swoole here.

  3. There may be a question that opcode is cached. If we update the code, will we still load the old opcode or recompile the opcode and cache it? We will summarize it separately later.

opcache configuration description

; Quick start opcache Cache.

; Is it cli On in mode opcache. 

; opcache Size of shared memory(Unit is M). 

; Memory size of reserved string(Unit is M). 

; stay hash The maximum number of script files stored in the table, ranging from 200 to 1000000. The reality is that{ 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 }The first prime number greater than or equal to the set value was found in. The minimum range is 200.

; Wasted memory online. If you exceed this online, opcache Will restart.

; If enabled, opcache Will be in hash Add a file directory after the script key of the table to avoid conflicts caused by eating scripts with the same name. Disabling it can improve performance, but it can also easily lead to application unavailability.

; If enabled(1),opcache It will judge whether the script is updated every set value time. If disabled(0),Script updates will not be detected automatically and must be restarted PHP Service, or use opcache_reset(),opcache_invalidate()Function to refresh the cache.

; opcache Time period to check whether the script is updated(The unit is seconds),If it is set to 0, check and update will be performed for each request validate_timestamps=0,This value does not take effect.

; If disabled, in unified include_path The following cached files will be reused, so the file with the same name under this path cannot be found.

; Save PHP Comment content in the script. If off, the cache is not PHP Comments in the code can reduce the volume of the file, but some dependent comments or comments will not be used.

; If enabled, the quick stop continuation event is used. The so-called quick stop recurring events refer to dependency Zend The memory management module of the engine releases the memory of all request variables at one time, rather than releasing each allocated memory block in turn.
; stay php7.2.0 Start, be removed, such events will be in PHP Automatic processing in.

; If enabled, the file_exists(),is_file()and is_readable()Function, the opcode is detected whether the file is cached or not. If disabled, some old data may be read.

; The control optimization level is a binary bit mask.

; The path to the configuration file that is not optimized for compilation. This file configures which files are not compiled. If the beginning of each line in the text is";"At the beginning, it will be regarded as a comment. The file names in the blacklist can be wildcards or prefixes.
; For example, the path to the configuration file is"/home/blacklist.txt",Then the value of the configuration is the path.
; The configuration content can be in the following format

; This is a comment. When parsing, it starts with;,Is considered a comment


; The maximum file size of the cache in bytes. Set to 0 to cache all files.

; each N The second request will check the cache checksum, and 0 is not checked. This item has a great impact on performance and should be used in the debugging environment as far as possible.

; If the cache is inactive, wait for how many seconds before you plan to restart. If the set time is exceeded, the OPcache The module will kill the process holding the cache lock and restart it.

; The error log file location is not filled in. It will be output to the error log file of the server by default.

; Error log file level.
; By default, only fatal level (0) and error level (1) logs are logged. Other available levels are warning (2), information (3), and debugging (4).
; How to set more than 1 in progress force_restart_timeout Option, a warning message is inserted into the error log.

; opcache The preferred memory module is selected automatically if it is not configured. The values you can select are mmap,shm, posix as well as win32. 

; Protect shared memory from unexpected writes when executing scripts. For internal debugging only.

; Only characters beginning with a string are allowed PHP Script call opcache api Function, no restrictions by default.

; stay Windows The base address of the shared memory segment on the platform. be-all PHP Processes map shared memory to the same address space. Use this configuration instruction to avoid the "cannot reattach to base address" error.

; Configure the L2 cache directory and enable L2 cache. Enabling L2 caching allows you to SHM Memory full, server restart or reset SHM Improve performance when. The default value is an empty string "",Indicates that file based caching is disabled.

; Enable or disable in shared memory opcode Cache.

; Whether to verify the checksum of the file when loading the script from the file cache.

; stay Windows On the platform, file based caching is used when a process cannot be attached to shared memory. Need to open opcache.file_cache_only Options. It is recommended to enable this option, otherwise the process may not start.

; Enable or disable the PHP Copy code (text segment) to HUGE PAGES Yes. This configuration instruction can improve performance, but it needs to be OS The corresponding configuration is carried out at the level.

; Verify access to the cache file for the current user.

; stay chroot Avoid naming conflicts in your environment. To prevent the process from accessing chroot Files outside the environment should be chroot Enable this option if.

Configuration example

The following code is an example configuration officially given by PHP. It is recommended to use this configuration item for configuration, or you can configure it separately according to your actual situation.


Problem summary

  1. How do I update opcode?

The compiled opcode will be added to the shared memory. If we update the code, we need to update the opcode, otherwise the obtained code is still the old opcode. The situation mentioned at the beginning of the article will happen. There are several ways to solve this problem.

; Method 1
 Directly restart our php Process, but this will cause service interruption, which is not recommended.

; Method 2
 Set according to the official function. Use in code opcache_reset()Or use opcache_invalidate()Function to recharge opcode. You can execute this function directly through a special link.

; Method 3
 use php.ini The configuration items in realize automatic recharge opcode. 
opcache.validate_timestamps = 1
opcache.revalidate_freq  = 60

Effect demonstration

  1. In the above two figures, the first one is a pressure measurement when opcache is not enabled, and the second one is a pressure measurement when opcache is enabled.

  2. From the screenshot, there are some small improvements after opening opcache. There is no doubling of the promotion said on Internet.

  3. The promotion here cannot be said that the promotion effect of opcache is not obvious, which needs to be determined according to comprehensive factors. The use of Mac operation in the demonstration here will reduce a lot.

Tags: PHP Laravel

Posted on Sat, 25 Sep 2021 14:38:02 -0400 by Mr Chris