Home > Backend Development > PHP Tutorial > PHP Opcache optimization acceleration

PHP Opcache optimization acceleration

小云云
Release: 2023-03-22 12:08:01
Original
1591 people have browsed it

Opcache is a method that avoids the overhead of loading and parsing PHP scripts each time by storing the precompiled bytecode of the parsed PHP script in shared memory. The parser can directly read the cached bytes from the shared memory. code, thus greatly improving the execution efficiency of PHP. PS: It needs to be distinguished from the Xcache mechanism, and its use will be introduced in the subsequent summary.

· How to install

· How to configure

· How to use

· Display analysis

· Precautions

1. How to install

In PHP 5.5.0 and subsequent versions, PHP has embedded the Opcache function in the release version in the form of an expansion library. Opcache acceleration is not enabled by default, and developers need to use php. Just add or uncomment the Opcache related configuration in ini. For older versions, Opcache can be installed and configured as a PECL extension library.

NOTE:

If you use the --disable-all parameter to disable the build of the default extension, you must use the --enable-opcache option to enable Opcache.

2. How to configure

php.ini:

[opcache]

; Enable opcode caching

opcache.enable= 1

; Starting the opcode cache for the CLI version of PHP is generally used for testing and debugging

opcache.enable_cli=1

; Shared memory size in MB

opcache.memory_consumption=128

; Storage temporary string cache size, unit is MB, this configuration will be ignored before PHP5.3.0

opcache.interned_strings_buffer=8

; The maximum limit on the number of cached files, the hit rate is less than 100%, you can try to increase this value

opcache.max_accelerated_files=4000

; Check the modification time of the file within a certain period of time , set the check time period here, the default is 2, the unit is seconds

opcache.revalidate_freq=60

; Turn on the quick stop of the renewal event, relying on the memory management module of the Zend engine, once Release the memory of all request variables instead of releasing memory blocks sequentially

opcache.fast_shutdown=1

;Enable the function of checking the existence and readability of PHP scripts, regardless of whether the file has been cached , will check the opcode cache, which can improve performance. But if disabled The opcache.validate_timestamps option may risk returning stale data.

opcache.enable_file_override=1

; Extension library so file association loading

zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts -20131226/opcache.so

NOTE:

The configuration items listed above are commonly used and important configuration items, but there are actually more than just these configuration items.

3. How to use

In fact, the use of Opcache is mainly reflected in the several functions it provides:

1. opcache_get_configuration;

Format: array opcache_get_configuration(void);

Get the set cache configuration information, and return the configuration information, blacklist and version number in the form of an array.

2. opcache_get_status;

Form: array opcache_get_status(void);

Get the set cache status information.

3. opcache_invalidate;

Form: boolean opcache_invalidate (string);

The function of this function is to invalidate the bytecode cache of the specified script. If force is not set or FALSE is passed in, then the script cache will be invalid only when the modification time of the script is newer than the corresponding bytecode time.

4. opcache_reset;

Form: boolean opcache_reset(void);

This function will reset the entire bytecode cache. After calling opcache_reset(), all scripts will be reloaded and parsed the next time they are clicked.

5. opcache_compile_file;

Form: boolean opcache_compile_file (string);

You can compile and cache the script without running it.

6、opcache_is_script_cached

Form: boolean opcache_is_script_cached (string);

Determine whether a script has been cached in Opcache.

Below I will write a PHP script that encapsulates the above functions, which will also facilitate the maintenance and management of Opcache in the future. The details are as follows:

<?php
/**
 * 这个文件是对opcache优化器的几个
 * 函数的封装,作为一个工具脚本使用
 */
if(!extension_loaded("ZendOpcache")) {
      echo "You do nothave the Zend OPcache extension loaded , please open it up,then retry!";
}
/**
 * 函数操作封装类
 * 数组形式的结果,会转为json格式返回,不做显示上的处理
 * 这里主要处理的是影响Opcache缓存状态的操作,对于查看
 * Opcache各项指标的处理,可查看项目:opcache-status
 */
class OpcacheScriptModel{
      private $_configuration;
      private $_status;
      function __construct() {
            $this->_configuration =opcache_get_configuration();
            $this->_status =opcache_get_status();
      }
      // 获取配置信息
      public function getConfigDatas(){
            echo json_encode($this->_configuration);
      }
      // 获取状态信息
      public function getStatusDatas(){
            echo json_encode($this->_status);
      }
      // 指定某脚本文件字节码缓存失效
      public function invalidate($script){
            return opcache_invalidate($script);
      }
      // 重置或清除整个字节码缓存数据
      public function reset() {
            return opcache_reset();
      }
      // 无需运行,就可以编译并缓存脚本
      public function compile($file){
            return opcache_compile_file($file);
      }
      // 判断某个脚本是否已经缓存到Opcache
      public function isCached($script){
            return opcache_is_script_cached($script);
      }
}
// 获得对象
function getOpcacheDataModel(){
      // 初始化对象
      $dataModel = NULL;
      if(NULL ==$dataModel) {
            $dataModel = new OpcacheScriptModel();
      }
      return $dataModel;
}
?>
Copy after login

The above script tool is relatively simple. Generally, it can be placed in a project or used alone as a tool. It can be parsed and compiled when needed. In fact, the following display and analysis of open source projects also uses the above API function, but it will display the obtained data in a graphical form, so For more intuitive information, please continue reading.

4. Display analysis

We know that the execution mechanism of PHP scripts is that the parser parses the PHP script file and parses it into bytecode data, and the role of the Opcache optimizer is to cache The parsed bytecode data can be read directly from the cache without repeating the loading and parsing of the PHP script every time. Therefore, for the use of Opcache, we generally only need to do two things:

1. Use the Opcache optimizer to speed up the execution of the PHP program;

2. Through various indicators and parameters of Opcache, understand the performance status of the current PHP program in real time;

Then, we How to view and analyze the current Opcache acceleration effect? The answer is to use the open source project on Github: https://github.com/rlerdorf/opcache-status

Put the downloaded project into the root directory of the current Web server and access it directly , look at the effect first:


As can be seen from the above screenshots and project files, the Opcache tool is a simplified GUI version. Use It can clearly understand and analyze the following content:

1. Cache usage, remaining conditions, memory waste and proportion;

2. Cached keys, number of remaining keys;

3. Number of cache hits and misses;

4. Cache configuration, status and cache capture script;

5. Cache script files are divided and displayed intuitively in the form of views ;

Okay, that’s it for the visualization of Opcache. Let’s take a look at a few points to note.

5. Notes

1. It is not recommended to enable PHP optimization for Xcache and Opcache at the same time;

Because PHP 5.5.0 and subsequent versions have built-in support for Opcache, Therefore, PHP realizes its importance. Compared with third-party PHP optimizers such as Xcache, using Opcache will be a better choice. In addition, if both exist at the same time, the number of cache hits of Opcache will be greatly reduced and unnecessary overhead will be added.

2. It is not recommended to turn on Opcache during the development process

The reason is obvious. After turning on Opcache, the content modified by the developer will not be displayed and take effect immediately because it is affected by opcache.revalidate_freq=60 impact, so it is recommended to turn on Opcache when testing performance after development and testing. Of course, Opcache must always be turned on in the production environment.

3. It is not recommended to set the Opcache indicators too large

The configuration size of each Opcache indicator or whether to enable it needs to be combined with the actual needs of the project and the configuration recommended by Opcache official, and the actual situation of the project needs to be analyzed , which can be combined with the visual cache information analysis and adjustment in Part 4 above.

4. It is not recommended to use the old version of Opcache for a long time

It is recommended to pay attention to the news of Opcache official website in time to learn about its bug fixes, function optimization and new functions in real time, so as to better apply it in your own projects.

5. It is not recommended to put the open source project introduced above into the Web service root directory in a production environment. The reason is very simple, because this open source project does not have access restrictions and security processing. , that is to say, any user who can access the external network can directly access it as long as he knows the access address, so it is not safe. Generally, this open source tool only helps to visually analyze the performance of PHP, and is usually used during the development and debugging phase. If you just want to enable it in a production environment, you must do security restrictions.

Related recommendations:

Sharing how to use Opcache acceleration in PHP

The use of opcache in PHP

Summary of using Opcache for PHP optimization and acceleration

The above is the detailed content of PHP Opcache optimization acceleration. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template