php Zend Opcache,xcache,eAccelerator缓存优化详解(具体根据个人需要选择其一即可,功能都一样切勿重复选择)

来源:互联网 发布:java手机模拟器安卓版 编辑:程序博客网 时间:2024/06/05 05:45

XCACHE

XCache 是一个开源的 opcode 缓存器/优化器, 这意味着他能够提高您服务器上的 PHP 性能. 他通过把编译 PHP 后的数据缓冲到共享内存从而避免重复的编译过程, 能够直接使用缓冲区已编译的代码从而提高速度. 通常能够提高您的页面生成速率 2 到5 倍, 降低服务器负载.
 
XCache 是一个又快又稳定的 PHP opcode 缓存器. 经过良好的测试并在大流量/高负载的生产机器上稳定运行. 经过(在 linux 上)测试并支持所有现行 PHP 分支的最新发布版本, 如 PHP_4_3 PHP_4_4 PHP_5_0 PHP_5_1 PHP_5_2 HEAD(6.x), 并支持线程安全/Windows. 与同类 opcode 缓存器相比更胜一筹, 比如能够快速跟进 PHP 版本.
XCache 工程由 mOo 领队, 他也是 Lighttpd 的开发成员之一. Lighttpd 是最快的 Web 服务器应用程序之一, 并且超越 Apache 以及许多其他 Web 服务器. XCache 努力达到类似的效果.
 
XCache 的INI配置详解 
载入 XCache 模块


引用
;; 安装成 zend extension (推荐), 路径一般是 "$extension_dir/xcache.so"
zend_extension = /usr/local/lib/php/extensions/non-debug-non-zts-xxx/xcache.so
;; Windows 系统例子:
zend_extension_ts = c:/php/extensions/php_xcache.dll
;; 或者您也可把 XCache 安装成 extension, 注意确保您的 extension_dir 设置正确, 并
把 xcache.so 或者 php_xcache.dll 放到该目录里面
; extension = xcache.so
;; 或者 Win32 系统:
; extension = php_xcache.dll


XCache Administration

xcache.admin.user string
验证名.
xcache.admin.pass string
md5 后的验证密码, 亦即 md5(您的密码), 留空则禁用管理页面.
xcache.test string
仅在测试一些功能的时候才启用. 如果您不知道这个功能的作用, 则您不需要知道.
xcache.coredump_directory string
设置在 crash (SIGSEGV/SIGABRT) 时保存 core dump 文件的路径. 留空则禁止, 或者设置为类似 "/tmp/phpcore/" 的目录. 确保这个路径可以被 php 写入文件. (与 open_basedir 无关).
xcache.admin.enable_auth string
如果你打算自己处理验证, 用这个选项禁止 HTTP 验证功能. 值得注意的是任意 vhost 用户都可以安装一个 XCache admin 页面, 如果禁止了内建 HTTP 验证, 则他们亦不需要权限即可访问管理页面. 出于安全考虑, 您应该尽量考虑保留 XCache 内建验证功能, 针对 XCache admin 页面特定地址取消网页服务器的 mod_auth 这个选项仅在 1.2.x 系列有作用, 起始版本 1.2.1

XCache Cacher

xcache.cacher boolean
使用/不使用 opcode 缓存器. xcache.size = 0 时无效.
xcache.size int
0 禁止, 非 0 则启用缓存器. 请注意您系统所允许的 mmap 最大值.
xcache.count int
指定将 cache 切分成多少块. 参考 SplittedCache
xcache.slots size
只是作为 hash 槽个数的参考值, 您可以放心地缓冲超过这个个数的项目.
xcache.ttl seconds
设置缓冲项目的 Ttl (Time To Live) 值, 0=永不过期.
xcache.gc_interval seconds
检查过期项目, 回收内存空间的间隔.
xcache.var_size int
xcache.var_count int
xcache.var_slots size
xcache.var_gc_interval seconds
同上, 不过用于数据缓冲而不是 opcode 缓冲.
xcache.var_ttl seconds
xcache_(get|set|inc|dec) 等的默认 ttl 值.
xcache.var_maxttl seconds
最大 ttl 值, 程序无法指定超过这个最大值的 ttl.
xcache.readonly_protection boolean
如果启用了 ReadonlyProtection, 将会略微降低性能, 但是会提高一定的安全系数. 这个选项对于 xcache.mmap_path = /dev/zero 无效.
xcache.mmap_path string
对于 *nix, xcache.mmap_path 是 文件路径, 不是目录. 对于 Win32, xcache.mmap_path 只是匿名的 map 名, 不是实际的文件路径. 如果您要启用 ReadonlyProtection 请用类似 "/tmp/xcache" 的路径. 2 组 php 不该共用同一个路径 (/dev/zero 除外).

XCache Optimizer

xcache.optimizer boolean
启用优化器 (目前无效).

XCache Coverager

xcache.coverager boolean
Enable coverage data collecting for xcache.coveragedump_directory and xcache_coverager_start/stop/get/clean() functions (will hurt executing performance)
xcache.coveragedump_directory string
Directory to dump coverage data. Make sure it's readable (care open_basedir) by coverage viewer script. Requires xcache.coverager=On
 

eAccelerator

1、背景
eAccelerator 是一个免费开源的PHP加速、优化、编译和动态缓存的项目,它可以通过缓存PHP代码编译后的结果来提高PHP脚本的性能,使得一向很复杂和离我们很远的PHP脚本编译问题完全得到解决。通过使用eAccelerator,可以优化你的PHP代码执行速度,降低服务器负载,可以提高PHP应用执行速度最高达10倍。

eAccelerator 项目诞生于2004年,当时它是作为 Turck MMCache 项目的一个分支提出并投入开发的。 Turck MMCache 由 Dmitry Stogov 开发,是个非常优秀的PHP内存缓存加速系统,如今仍然有很大部分 eAccelerator 的代码应用到该项目中,目前该项目有很长时间没有更新了,对于最新的PHP版本支持还未推出。

2、原理
eAccelerator 通过把经过编译后的PHP代码缓存到共享内存中,并在用户访问的时候直接调用从而起到高效的加速作用。它的效率非常高,从创建共享内存到查找编译后的代码都在非常短的时间内完成,对于不能缓存到共享内存中的文件和代码,eAccelerator还可以把他们缓存到系统磁盘上。

eAccelerator 同样还支持PHP代码的编译和解释执行,你可以通过encoder.php脚本来对php代码进行编译达到保护代码的目的,经过编译后的代码必须运行在安装了eAccelerator的环境下。eAccelerator编译后的代码不能被反编译,它不象其他一些编译工具那样可以进行反编译,这将使得代码更加安全和高效。

最新的PHP5.4.8安装eAccelerator,

需要注意的是要安装高版本的,低了编译不过去。

官网:http://eaccelerator.net/

 

1.下载安装eAccelerator

#wget https://github.com/eaccelerator/eaccelerator/tarball/master

最新的版本是eaccelerator-42067ac.tar.gz

#tar zxvf eaccelerator-42067ac.tar.gz

需要phpize安装php扩展,如果不明白phpize可以看这个:http://blog.csdn.net/21aspnet/article/details/8193482

需要注意的是需要写php的安装路径对应的phpize下面的php-config也是

#  /usr/local/webserver/php/bin/phpize

需要记住生成的提示信息下面配置php要用到

/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-

20100525/

#./configure --enable-eaccelerator=shared --with-php-config=/usr/local/webserver/php/bin/php-config

# make

需要注意的是要安装高版本的,低了编译不过去。

# make install

 

2.配置php.ini配置文件

[eaccelerator]
extension="/data/webserver/php/lib/php/extensions/no-debug-zts-20060613/eaccelerator.so"
eaccelerator.shm_size="32"
eaccelerator.cache_dir="/data/cache/eaccelerator"
eaccelerator.enable="1"
eaccelerator.optimizer="1" (如果没有安装optimizer请设置为0关闭加速引擎,否则会出现PHP脚本错误)
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"
  
建立缓存目录:
# mkdir -p /data/cache/eaccelerator
# chmod 0777 /data/cache/eaccelerator
  
重启Apache:
# service httpd restart
3、检查ZendOptimizer和eaccelerator是否安装成功
  
创建一个phpinfo.php文件,内容如下:
  <?php
      phpinfo();
  ?>
  
  将该文件放置到网站目录,在浏览器中访问,如果出现以下内容则安装成功:
  This program makes use of the Zend Scripting Language Engine:
  Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
      with eAccelerator v0.9.5, Copyright (c) 2004-2006 eAccelerator, by eAccelerator
      with Zend Extension Manager v1.0.11, Copyright (c) 2003-2006, by Zend Technologies
      with Zend Optimizer v3.2.2, Copyright (c) 1998-2006, by Zend Technologies
  
  
  
  二、eaccelerator配置信息详解(根据官方英文说明翻译)
  
  extension="/data/webserver/php/lib/php/extensions/no-debug-zts-20060613/eaccelerator.so"
  
  解释:PHP扩展eaccelerator.so的路径。
  
  --------------------
  
  eaccelerator.shm_size="32"
  
  解释:eaccelerator可使用的共享内存大小(单位为MB)。
  
  在Linux下,单个进程的最大内存使用量受/proc/sys/kernel/shmmax中设置的数字限制(单位为字节),例如CentOS 4.4的shmmax默认值为33554432字节(33554432bytes/1024/1024=32MB)。
  
  临时更改该值:
  # echo 字节数 > /proc/sys/kernel/shmmax
  
  按照以上方法更改,在每次重启系统时,该值会被自动还原。如果想永久更改,可以修改/etc/sysctl.conf文件,设置:
  kernel.shmmax = 字节数
  
  --------------------
  
  eaccelerator.cache_dir="/data/cache/eaccelerator"
  
  解释:缓存路径,可以使用命令mkdir -p /data/cache/eaccelerator创建该目录,然后使用命令chmod 0777 /data/cache/eaccelerator设置该目录权限为0777
  
  --------------------
  
  eaccelerator.enable="1"
  
  解释:打开或者关闭eaccelerator。"1"指打开,"0"指关闭。默认值为"1"。
  
  --------------------
  
  eaccelerator.optimizer="1"  (如果没有安装optimizer请设置为0关闭加速引擎,否则会出现PHP脚本错误)

  解释:打开或者关闭代码优化,开启可以加快代码的执行速度。"1"指打开,"0"指关闭。默认值为"1"。
  
  --------------------
  
  eaccelerator.check_mtime="1"
  
  解释:当打开此项时,eaccelerator会在每次请求时检查php文件的修改时间,看其是否被修改过,这会耗费一点时间,如果php文件被修改过,eaccelerator会重新编译缓存该php文件。当关闭此项时,如果php文件被修改,则需要手工删除eaccelerator缓存,才能显示被修改的php文件。"1"指打开,"0"指关闭。默认值为"1"。
  
  --------------------
  
  eaccelerator.debug="0"
  
  解释:打开或者关闭调试记录。当打开时,eaccelerator会将对一个缓存文件的每次请求都写进log。打开此项只对调试eaccelerator是否有BUG时有益处。"1"指打开,"0"指关闭。默认值为"0"。
  
  --------------------
  
  eaccelerator.filter=""
  
  解释:决定哪些PHP文件应该被缓存。可以指定一个范围(比如"*.php *.phtml"),这样被指定的文件就会被缓存。如果该范围以!开头,被指定的文件就不会被缓存。默认值为"",表示缓存所有的PHP文件。
  
  --------------------
  
  eaccelerator.shm_max="0"
  
  解释:一个用户使用例如eaccelerator_put之类的函数能够往共享内存中加载的最大数据。默认值为"0",表示不限制。(单位为字节)
  
  --------------------
  
  eaccelerator.shm_ttl="0"
  
  解释:当没有足够的空闲共享内存去尝试缓冲一个新脚本时,将删除至少在shm_ttl秒之前没有被访问过的文件。默认值为"0",表示不尝试从共享内存中删除任何旧的脚本。(单位为秒)
  
  --------------------
  
  eaccelerator.shm_prune_period="0"
  
  解释:当没有足够的空闲共享内存去尝试缓冲一个新脚本时,将删所有旧脚本,前提是这个尝试在超过shm_prune_period秒之前被执行过。默认值为"0",表示不尝试从共享内存中删除任何旧的脚本。(单位为秒)
  
  --------------------
  
  eaccelerator.shm_only="0"
  
  解释:打开或者关闭在磁盘上缓存编译过的脚本。这个参数对会话数据和内容缓存没有效果。默认值为"0",表示使用磁盘和共享内存来缓存。
  
  --------------------
  
  eaccelerator.compress="1"
  
  解释:打开或者关闭缓存内容压缩。"1"指打开,"0"指关闭。默认值为"1"。
  
  --------------------
  
  eaccelerator.compress_level="9"
  
  解释:内存压缩的级别。默认值为"9",表示最大压缩。



#这个是我机器的so位置
extension="/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20100525/eaccelerator.so"
#这个是设置一个缓存大小
eaccelerator.shm_size="64"
#缓存目录
eaccelerator.cache_dir="/usr/local/webserver/eaccelerator_cache" 实际配置不建议放在WEB目录下,考虑到安全因素建议放到web目录以外

#网站目录,把解开的eAccelerator 的源码包里的control.php 文件复制到你的WEB 服务器中的一个目录下,使其它以通过http 访问,如果不加那么看不到缓存的页面列表,但是还是可以看到内存信息

eaccelerator.allowed_admin_path=/usr/www/

eaccelerator.enable="1"
eaccelerator.optimizer="1" (如果没有安装optimizer请设置为0关闭加速引擎,否则会出现PHP脚本错误)
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"

eaccelerator.keys     = "disk_only"
eaccelerator.sessions = "disk_only"
eaccelerator.content  = "disk_only"

设置内容缓存的存放的地方,可以设置为:
shm_and_disk 在共享缓存和硬盘(默认值)
shm      默认存在共享内存,如果共享内存已满或大小超过 "eaccelerator.shm_max" 的值,就存到硬盘
shm_only    只存放在共享内存
disk_only    只存放在硬盘
none      不缓存数据

这里为了查看效果设置为存在硬盘

 

增加权限

#mkdir /usr/local/webserver/eaccelerator_cache
#chmod 777 /usr/local/webserver/eaccelerator_cache

 

3.测试查看phpinfo()

 

4.查看缓存文件夹

为了直观所以截图图形界面

这说明成功生成了缓存

 

5.更好的监控方式

eAccelerator控制面板的地址,安装包里有一个control.php文件,把它复制到网站的任意目录,可以用它查看和管理,这个必须指定,否则查看缓存内容的时候会出错,访问时候默认的用户名是:admin,密码:eAccelerator

 

注意,之前的php.ini配置文件加上这个配置就会看到明细信息

eaccelerator.allowed_admin_path=/usr/www/

 

重启apache则会清空缓存

 

文档:

eaccelerator.shm_size="8"
eAccelerator 可以使用的共享内存的数量 (以MB为单位) . "0" 是指操作系统的默认值,默认值是 "0",可根据服务器的实际情况来调整:16、32、64、128都是可以的。

eaccelerator.cache_dir="/usr/local/webserver/eaccelerator_cache"
这个目录是给磁盘缓存使用,eAccelerator 在这里储存预先编译好的代码,进程数据,内容以及用户的自定义内容。同样的数据也能被储存在共享内存中 (这样可以提高访问速度)

eaccelerator.enable="1"
开启或关闭 eAccelerator,"1" 为开启,"0" 为关闭。默认值为 "1"。

eaccelerator.optimizer="1" (如果没有安装optimizer请设置为0关闭加速引擎,否则会出现PHP脚本错误)
启或关闭内部优化器,可以提升代码执行速度。"1" 为开启,"0" 为关闭。默认值为 "1"。

eaccelerator.check_mtime="1"
打开或者关闭 PHP 的文件修改检查,"1" 是指打开,"0" 是指关闭。默认值是 "1"。

eaccelerator.debug="0"
开启或关闭调试日志记录。"1" 为开启,"0" 为关闭。默认值为 "0"。会将缓存命中得记录写入日志。

eaccelerator.filter=""
判断哪些 PHP 文件必须缓存。可以指定缓存和不缓存的文件类型(如 "*.php *.phtml"等)如果参数以 "!" 开头,则匹配这些参数的文件被忽略缓存。默认值为 "",即,所有 PHP 文件都将被缓存。

eaccelerator.shm_max="0"
当使用 " eaccelerator_put() " 函数时禁止其向共享内存中存储过大的文件。该参数指定允许存储的最大值,单位:字节 (10240, 10K, 1M)。"0" 为不限制。默认值为 "0"。

eaccelerator.shm_ttl="3600"
当 eAccelerator 获取新脚本的共享内存大小失败时,它将从共享内存中删除所有在最后 "shm_ttl" 秒内没有存取的脚本缓存。默认值为"0",为不从共享内存中删除任何缓存文件。

eaccelerator.shm_prune_period="3600"
当 eAccelerator 获取新脚本的共享内存大小失败时,他将试图从共享内存中删除早于"shm_prune_period" 秒的缓存脚本。默认值为 "0",为不从共享内存中删除任何缓存文件。

eaccelerator.shm_only="0"
允许或禁止将已编译脚本缓存在磁盘上。该选项对 session 数据和内容缓存无效。默认值为 "0",为使用磁盘和共享内存进行缓存。

eaccelerator.compress="1"
允许或禁止压缩内容缓存。默认值为 "1",为允许压缩。

eaccelerator.compress_level="9"
指定内容缓存的压缩等级。默认值为 "9",为最高等级。

eaccelerator.keys = "disk_only"
eaccelerator.sessions = "disk_only"
eaccelerator.content = "disk_only"
设置内容缓存的存放的地方,可以设置为:
shm_and_disk 在共享缓存和硬盘(默认值)
shm      默认存在共享内存,如果共享内存已满或大小超过 "eaccelerator.shm_max" 的值,就存到硬盘
shm_only    只存放在共享内存
disk_only    只存放在硬盘
none      不缓存数据

 

6.测试性能

快速排序代码

[php] view plaincopyprint?
  1. <?php  
  2. function quickSort($arr)  
  3. {  
  4.     $len    = count($arr);  
  5.     if($len <= 1) {  
  6.         return $arr;  
  7.     }  
  8.     $key = $arr[0];  
  9.     $left_arr    = array();  
  10.     $right_arr    = array();  
  11.   
  12.     for($i=1; $i<$len$i++){  
  13.         if($arr[$i] <= $key){  
  14.             $left_arr[] = $arr[$i];  
  15.         } else {  
  16.             $right_arr[] = $arr[$i];  
  17.         }  
  18.     }  
  19.   
  20.     $left_arr    = quickSort($left_arr);  
  21.     $right_arr    = quickSort($right_arr);  
  22.     return array_merge($left_arrarray($key), $right_arr);  
  23. }  
  24.   
  25.   
  26. $arr = array(6,3,8,5,9,2,10);  
  27. echo '<pre>';  
  28. print_r(quickSort($arr));  
  29. ?>  
[php] view plaincopyprint?
  1. <?php  
  2. function quickSort($arr)  
  3. {  
  4.     $len    = count($arr);  
  5.     if($len <= 1) {  
  6.         return $arr;  
  7.     }  
  8.     $key = $arr[0];  
  9.     $left_arr    = array();  
  10.     $right_arr    = array();  
  11.   
  12.     for($i=1; $i<$len$i++){  
  13.         if($arr[$i] <= $key){  
  14.             $left_arr[] = $arr[$i];  
  15.         } else {  
  16.             $right_arr[] = $arr[$i];  
  17.         }  
  18.     }  
  19.   
  20.     $left_arr    = quickSort($left_arr);  
  21.     $right_arr    = quickSort($right_arr);  
  22.     return array_merge($left_arrarray($key), $right_arr);  
  23. }  
  24.   
  25.   
  26. $arr = array(6,3,8,5,9,2,10);  
  27. echo '<pre>';  
  28. print_r(quickSort($arr));  
  29. ?>  


 

测试方法

#ab -n 1000 http://192.168.2.107/quicksort.php

连续测试几次,主要的性能指标是Requests per second

 

左边是没有使用eAccelerator 时的情况,右边是使用了的

连续测试10次,基本数据还是比较稳定的。

使用了eAccelerator 时比没使用的要好!

使用strace查看C语言级别的php源码       

可以看eAccelerator缓存是怎么被读取的完成过程

 

扩展阅读:

eAccelerator提供如下的API接口和文件:(下述文件均在源码包的doc/php/目录下)

文件列表:

cache.php

dasm.php

encoder.php

info.php

loader.php

session.php

shared_memory.php

接口列表:

array eaccelerator_cached_scripts ()

void eaccelerator_cache_output (string $key, string $eval_code, [int $ttl = 0])

void eaccelerator_cache_page (string $key, [int $ttl = 0])

void eaccelerator_cache_result (string $key, string $code, [int $ttl = 0])

void eaccelerator_caching (boolean $flag)

void eaccelerator_clean ()

void eaccelerator_clear ()

array eaccelerator_dasm_file (mixed $filename)

mixed eaccelerator_encode (mixed $src, [mixed $prefix = ''], [string $pre_content = ''], [string $post_content = ''])

void eaccelerator_gc ()

mixed eaccelerator_get (string $key)

array eaccelerator_info ()

array eaccelerator_list_keys ()

void eaccelerator_load ()

boolean eaccelerator_lock (string $key)

void eaccelerator_optimizer (boolean $flag)

void eaccelerator_purge ()

boolean eaccelerator_put (string $key, mixed $value, [int $ttl = 0])

array eaccelerator_removed_scripts ()

boolean eaccelerator_rm (string $key)

void eaccelerator_rm_page (string $key)

boolean eaccelerator_set_session_handlers ()

boolean eaccelerator_unlock (string $key)

有关上述文档详细说明请参考官方文档

下面有部分网友翻译后的接口说明:

eaccelerator_put($key, $value, $ttl=0)
   将 $value 以 $key 为键名存进缓存(php4下支持对像类型,看源码好像zend2里不支持了),$ttl 是这个缓存的生命周期,单位是秒,省略该参数或指定为 0 表示不限时,直到服务器重启清空为止。
 
eaccelerator_get($key)
   根据 $key 从缓存中返回相应的 eaccelerator_put() 存进去的数据,如果这项缓存已经过期或不存在那么返回值是 NULL
 
eaccelerator_rm($key)
   根据 $key 移除缓存
 
eaccelerator_gc()
   移除清理所有已过期的 key
 
eaccelerator_lock($key)
   为 $key 加上锁定操作,以保证多进程多线程操作时数据的同步。需要调用 eaccelerator_unlock($key) 来释放这个锁或等待程序请求结束时自动释放这个锁。
   例如:
   <?php
     eaccelerator_lock(“count”);
     eaccelerator_put(“count”,eaccelerator_get(“count”)+1));
   ?>
 
eaccelerator_unlock($key)
   根据 $key 释放锁
 
eaccelerator_cache_output($key, $eval_code, $ttl=0)
   将 $eval_code 代码的输出缓存 $ttl 秒,($ttl参数同 eacclerator_put)
   例如:
   <?php eaccelerator_cache_output(‘test’, ‘echo time(); phpinfo();’, 30); ?>
 
eaccelerator_cache_result($key, $eval_code, $ttl=0)
   将 $eval_code 代码的执行结果缓存 $ttl 秒,($ttl参数同 eacclerator_put),类似 cache_output
   例如:
   <?php eaccelerator_cache_result(‘test’, ‘ time() . “Hello”;’, 30); ?>
 
eaccelerator_cache_page($key, $ttl=0)
   将当前整页缓存 $ttl 秒。
   例如:
   <?php
     eaccelerator_cache_page($_SERVER['PHP_SELF'].’?GET=’.serialize($_GET),30);
     echo time();
     phpinfo();
   ?>
 
eaccelerator_rm_page($key)
   删除由  eaccelerator_cache_page() 执行的缓存,参数也是 $key

2、PHP代码中使用eAccelerator加速

另外,在PHPCMS里面已经集成了对eAccelerator的支持,下面是一段来自PHPCMS里面的代码

class cache{    function __construct()    {    }    function cache()    {$this->__construct();    }    function get($name)    {        return eaccelerator_get($name);    }    function set($name, $value, $ttl = 0)    {        eaccelerator_lock($name);        return eaccelerator_put($name, $value, $ttl);    }    function rm($name)    {        return eaccelerator_rm($name);    }    function clear()    {        return eaccelerator_gc();    }}


 

新一代 PHP 加速插件 Zend Opcache

大家知道目前PHP的缓存插件一般有三个:APC、eAccelerator、XCache,但未来它们可能都会消失,因为PHP 5.5已经集成Zend Opcache,功能和前三者相似但又有少许不同,缓存速度据说比它们更快(注意:只是据说,我没测试过)。

这几个PHP加速插件的主要原理都相同,就是把PHP执行后的数据缓冲到内存中从而避免重复的编译过程,能够直接使用缓冲区已编译的代码从而提高速度,降低服务器负载,它们的效率是显而易见的,像drupal这种庞大的CMS,每次打开一个页面要调用数十个PHP文件,执行数万行代码,效率可想而知,在安装APC等加速器后打开页面的速度明显加快。

Zend Opcache 已经集成在了PHP 5.5里面,编译安装PHP5.5的时候加上--enable-opcache就行了。但也支持低版本的 PHP 5.2.*, 5.3.*, 5.4.*,未来会取消对5.2的支持,下面是我在PHP 5.4下的安装方法:

依次执行下面的命令

wget http://pecl.php.net/get/zendopcache-7.0.2.tgztar xzf zendopcache-7.0.2.tgzcd zendopcache-7.0.2/usr/local/php/bin/phpize (此处根据实际php安装路径)./configure --with-php-config=/usr/local/php/bin/php-configmakemake install


如果显示Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-zts-20100525/ 表示安装完成,下面要修改php的配置文件让它生效

接着呢,配置下php.ini,在最后加上:

[opcache]
zend_extension=opcache.so
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=1
opcache.enable=1

一般来说,按照以往的经验,如果加在ZendGuardLoader之前会稳定多了。

 

 

128意思是给它分配128M内存,然后重启apache,用phpinfo查看是否生效,显示下面的信息就说明生效了



在phpinfo页面的下面可以看到的运行状态



如果嫌这个不直观可以装个PHP文件查看,地址在https://gist.github.com/ck-on/4959032,把上面的代码保存为一个php文件放到你的网站目录下面打开就可以看到:



命中率100%。

Zend Opcache因为最近才出来,现在还是测试版,相信在未来几年会越来越流行,现在真没多少人用。目前测试来看还比较稳定,我已经在 vbulletin论坛下运行了几天,不过没看出和APC、xcache有啥区别,只是最近我的APC老让apache崩溃(可能是apache和php版本太新的原因),想换个试试,毕竟Zend Opcache和APC都是php官方的,值得信赖。

zend Opcache配置参数详解

我的最终如下,其余参数默认即可。
    opcache.memory_consumption=512
    opcache.max_accelerated_files=16229
    opcache.revalidate_freq=864000
    ;如果十天半月不改动 php 代码,上面的值尽可能高,单位是秒。
    ;如果改了,要么重启 apache,要么去上面那个控制面板里“Recheck”。
    opcache.enable_file_override=1
    opcache.force_restart_timeout=30

OPcache 配置参数中文版如下...(中文和英文同样让人难懂,两种语言文档都啃过了,基本才会了解...):
    opcache.enable(默认值:1)
    Zend Optimizer + 的开关, 关闭时代码不再优化.
    
    opcache.memory_consumption(默认值:64)
    Zend Optimizer + 共享内存的大小, 总共能够存储多少预编译的 PHP 代码(单位:MB).
    
    opcache.interned_strings_buffer(默认值:4)
    Zend Optimizer + 中interned字符串的占内存总量.(单位:MB)
    
    opcache.max_accelerated_files(默认值:2000)
    Zend Optimizer + 哈希表中键数量的最大值(一个脚本文件应当是对应一个key的,所以应当就是允许缓存的文件最大数量).
    这个值实际上是素数列表{ 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 }中第一个大于设定值的数字.
    值设定范围: 200 – 100000
    
    opcache.max_wasted_percentage(默认值:5)
    “浪费”的内存达到此值对应的百分比,就会发起一个重启调度.
    
    opcache.use_cwd(默认值:1)
    开启这条指令, Zend Optimizer + 会自动将当前工作目录的名字追加到脚本键上, 以此消除同名文件间的键值命名冲突。
    关闭这条指令会提升性能,但是会对已存在的应用造成破坏.
    
    opcache.validate_timestamps(默认值:1)
    禁用时, 您必须手动重置Zend Optimizer +或重新启动Web服务器,以使文件系统的更改生效.
    检查的频率是由指令 “opcache.revalidate_freq” 控制.
    
    opcache.revalidate_freq(默认值:2)
    多久(以秒为单位)检查文件时间戳以改变共享内存的分配.”1″ 表示一秒校验一次, 但是是每个请求一次. “0″ 表示总是在校验.
    
    opcache.revalidate_path(默认值:0)
    允许或禁止在 include_path 中进行文件搜索的优化. 如果文件搜索被禁用而且可以在相同的 include_path 中找到这个缓存的文件,
    文件搜索就不会再进行下去了. 因此,如果 include_path 其它地方有一个同名文件的话, 那就找不到了.
    如果这个优化对您的应用有影响,那么应当允许它搜索. 默认情况下,指令是禁止的,这就意味着,优化是处于激活状态的.
    
    opcache.save_comments(默认值:1)
    如果禁用,所有的文档注释都从代码中剔除以此减少优化过的代码的大小.
    禁用 “文档注释” 可能会破坏一些现有的应用和框架(例如: Doctrine, ZF2, PHPUnit).
    
    opcache.load_comments(默认值:1)
    如果禁用, PHP文档注释将不会从 SHM(共享内存) 中读取. 尽管”文档注释”还是会被存储(save_comments=1),
    但是那些无论如何都用不上的注释就不必被应用读取了.
    
    opcache.fast_shutdown(默认值:0)
    如果开启, 一个快速关闭队列用以提速代码. 快速关闭队列并不释放每个已分配的块, 而是让 Zend 引擎内存管理器来干这个活.
    
    opcache.enable_file_override(默认值:0)
    允许覆盖文件存在(file_exists等)的优化特性。
    
    opcache.optimization_level(默认值:0xffffffff)
    一个位掩码,其中每个位允许或禁用相应的缓存通过.
    
    opcache.inherited_hack(默认值:1)
    启用此Hack可以暂时性的解决”can’t redeclare class”错误. Zend Optimizer + 存储着 DECLARE_CLASS 操作码使用继承的地方
    (这些是唯一可以被PHP执行的操作码,但是也可能因为优化引起的父类找不到而无法执行).
    当文件被读取时, Optimizer 会试着通过当前环境绑定被继承的类.
    这样做的问题是. DECLARE_CLASS 的操作码可能不被当前脚本所需要, 如果脚本需要操作码至少完成类的定义操作, 那么它就会无法执行.
    这指令的默认是禁用的, 这就表示优化是有效的. 该在 php 5.3 以及以上的版中不再被需要, 而且这个设置也不会生效.
    
    opcache.dups_fix(默认值:0)
    启用此Hack可以暂时性的解决”can’t redeclare class”错误.
    
    opcache.blacklist_filename(默认值:无)
    Zend Optimizer + 黑名单文件的位置.
    Zend Optimizer + 黑名单是一个文本文件包含了那些不能被加速的文件名.文件格式为每行一个文件名.
    文件名须为一个完整的路径或者紧紧一个文件前缀
    (如:/var/www/x 屏蔽了 /var/www 文件和目录中所有以 ‘x’ 开始的文件或者目录). 需要屏蔽的文件通常符合下面三个原因中的一个:
    1) 目录包含了自动生成的代码, 如 Smarty 或者 ZFW 的缓存.
    2) 执行加速时代码无法很好的运行, 从而耽误了编译时评估.
    3) 代码触发了一个 Zend Optimizer + 的 Bug
    
    opcache.max_file_size(默认值:0)
    通过文件大小屏除大文件的缓存.默认情况下所有的文件都会被缓存.
    
    opcache.consistency_checks(默认值:0)
    每 N 次请求检查一次缓存校验.默认值0表示检查被禁用了.由于计算校验值有损性能,这个指令应当紧紧在开发调试的时候开启.
    
    opcache.force_restart_timeout(默认值:180)
    从缓存不被访问后,等待多久后(单位为秒)调度重启.Zend Optimizer + 依托此指令来确定一个进程可能在处理过程中出现问题的情况.
    这段时间(等待时间)过后, 假设 Zend Optimizer + 发生了一些问题, 并开始干掉那些仍然持有预防重启锁的进程.
    当这些发生时, 如果日志的级别是3级或以上, 一个 “killed locker” 的错误就会被记录到 Apache 的日志中.
    
    opcache.error_log(默认值:无)
    Zend Optimizer + 的错误日志文件名.留空表示使用标准错误输出(stderr).
    
    opcache.log_verbosity_level(默认值:1)
    将错误信息都导向 Web 服务器日志.默认的只有致命错误(level 0) 或者错误(level 1)才会被记录.
    你也可以允许警告(level 2),提示消息(level 3) 或者 调试消息(level 4)被记录下来.
    
    opcache.preferred_memory_model(默认值:无)
    内存共享的首选后台.留空则是让系统选择.
    
    opcache.protect_memory(默认值:0)
    防止共享内存在脚本执行期间被意外写入, 仅用于内部调试.
    
    opcache.mmap_base(默认值:无)
    共享内存段映射基础(仅适用于Windows).所有的PHP进程必须映射到相同的共享内存地址空间.
    该指令用于手动修复 “Unable to reattach to base address” 错误.

Zend Opcache之可视化PHP源代码:

因为官方源码下载地址偶尔经常出现无法打开的问题,所以这里直接给出了zend opcache的可视化源代码,直接复制即可!

[php] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <?php  
  2.  /* 
  3.  OCP - Opcache Control Panel   (aka Zend Optimizer+ Control Panel for PHP) 
  4.  Author: _ck_   (with contributions by GK, stasilok) 
  5.  Version: 0.1.6 
  6.  Free for any kind of use or modification, I am not responsible for anything, please share your improvements 
  7.  
  8.  
  9.  * revision history 
  10.  0.1.6  2013-04-12  moved meta to footer so graphs can be higher and reduce clutter 
  11.  0.1.5  2013-04-12  added graphs to visualize cache state, please report any browser/style bugs 
  12.  0.1.4  2013-04-09  added "recheck" to update files when using large revalidate_freq (or validate_timestamps=Off) 
  13.  0.1.3  2013-03-30  show host and php version, can bookmark with hashtag ie. #statistics - needs new layout asap 
  14.  0.1.2  2013-03-25  show optimization levels, number formatting, support for start_time in 7.0.2 
  15.  0.1.1  2013-03-18  today Zend completely renamed Optimizer+ to OPcache, adjusted OCP to keep working 
  16.  0.1.0  2013-03-17  added group/sort indicators, replaced "accelerator_" functions with "opcache_" 
  17.  0.0.6  2013-03-16  transition support as Zend renames product and functions for PHP 5.5 (stasilok) 
  18.  0.0.5  2013-03-10  added refresh button (GK) 
  19.  0.0.4  2013-02-18  added file grouping and sorting (click on headers) - code needs cleanup but gets the job done 
  20.  0.0.2  2013-02-14  first public release 
  21.  
  22.  
  23.  * known problems/limitations: 
  24.  Unlike APC, the Zend OPcache API 
  25.   - cannot determine when a file was put into the cache 
  26.   - cannot change settings on the fly 
  27.   - cannot protect opcache functions by restricting execution to only specific scripts/paths 
  28.  
  29.  
  30.  * todo: 
  31.  Extract variables for prefered ordering and better layout instead of just dumping into tables 
  32.  File list filter 
  33.  
  34.  
  35.  */  
  36.   
  37.   
  38.  // ini_set('display_errors',1); error_reporting(-1);  
  39.  if ( count(get_included_files())>1 || php_sapi_name()=='cli' || empty($_SERVER['REMOTE_ADDR']) ) { die; }  // weak block against indirect access  
  40.   
  41.   
  42.  $time=time();  
  43.  define('CACHEPREFIX',function_exists('opcache_reset')?'opcache_':(function_exists('accelerator_reset')?'accelerator_':''));  
  44.   
  45.   
  46.  if ( !empty($_GET['RESET']) ) {   
  47. if ( function_exists(CACHEPREFIX.'reset') ) { call_user_func(CACHEPREFIX.'reset'); }  
  48. header( 'Location: '.str_replace('?'.$_SERVER['QUERY_STRING'],'',$_SERVER['REQUEST_URI']) );   
  49. exit;  
  50.  }  
  51.   
  52.   
  53.  if ( !empty($_GET['RECHECK']) ) {  
  54. if ( function_exists(CACHEPREFIX.'invalidate') ) {   
  55. $recheck=trim($_GET['RECHECK']); $files=call_user_func(CACHEPREFIX.'get_status');  
  56. if (!empty($files['scripts'])) {   
  57. foreach ($files['scripts'as $file=>$value) {   
  58. if ( $recheck==='1' || strpos($file,$recheck)===0 )  call_user_func(CACHEPREFIX.'invalidate',$file);   
  59. }   
  60. }  
  61. header( 'Location: '.str_replace('?'.$_SERVER['QUERY_STRING'],'',$_SERVER['REQUEST_URI']) );   
  62. else { echo 'Sorry, this feature requires Zend Opcache newer than April 8th 2013'; }  
  63. exit;  
  64.  }  
  65.   
  66.   
  67.  ?><!DOCTYPE html>  
  68.  <html>  
  69.  <head>  
  70. <title>OCP - Opcache Control Panel</title>  
  71. <meta name="ROBOTS" content="NOINDEX,NOFOLLOW,NOARCHIVE" />  
  72.   
  73.   
  74.  <style type="text/css">  
  75. body {background-color: #fff; color: #000;}  
  76. body, td, th, h1, h2 {font-family: sans-serif;}  
  77. pre {margin: 0px; font-family: monospace;}  
  78. a:link,a:visited {color: #000099; text-decoration: none;}  
  79. a:hover {text-decoration: underline;}  
  80. table {border-collapse: collapse;}  
  81. .center {text-align: center;}  
  82. .center table { margin-left: auto; margin-right: auto; text-align: left;}  
  83. .center th { text-align: center !important; }  
  84. .middle {vertical-align:middle;}  
  85. td, th { border: 1px solid #000; font-size: 75%; vertical-align: baseline;}  
  86. h1 {font-size: 150%;}  
  87. h2 {font-size: 125%;}  
  88. .p {text-align: left;}  
  89. .e {background-color: #ccccff; font-weight: bold; color: #000; width:50%; white-space:nowrap;}  
  90. .h {background-color: #9999cc; font-weight: bold; color: #000;}  
  91. .v {background-color: #cccccc; color: #000;}  
  92. .vr {background-color: #cccccc; text-align: right; color: #000; white-space: nowrap;}  
  93. .b {font-weight:bold;}  
  94. .white, .white a {color:#fff;}   
  95.   
  96. img {float: right; border: 0px;}  
  97. hr {width: 600px; background-color: #cccccc; border: 0px; height: 1px; color: #000;}  
  98. .meta, .small {font-size: 75%; }  
  99. .meta {margin: 2em 0;}  
  100. .meta a, th a {padding: 10px; white-space:nowrap; }  
  101. .buttons {margin:0 0 1em;}  
  102. .buttons a {margin:0 15px; background-color: #9999cc; color:#fff; text-decoration:none; padding:1px; border:1px solid #000; display:inline-block; width:5em; text-align:center;}  
  103. #files td.v a {font-weight:bold; color:#9999cc; margin:0 10px 0 5px; text-decoration:none; font-size:120%;}  
  104. #files td.v a:hover {font-weight:bold; color:#ee0000;}  
  105. .graph {display:inline-block; width:145px; margin:1em 0 1em 1px; border:0; vertical-align:top;}  
  106. .graph table {width:100%; height:150px; border:0; padding:0; margin:5px 0 0 0; position:relative;}  
  107. .graph td {vertical-align:middle; border:0; padding:0 0 0 5px;}  
  108. .graph .bar {width:25px; text-align:right; padding:0 2px; color:#fff;}  
  109. .graph .total {width:34px; text-align:center; padding:0 5px 0 0;}  
  110. .graph .total div {border:1px dashed #888; border-right:0; height:99%; width:12px; position:absolute; bottom:0; left:17px; z-index:-1;}  
  111. .graph .total span {background:#fff; font-weight:bold;}  
  112. .graph .actual {text-align:right; font-weight:bold; padding:0 5px 0 0;}   
  113. .graph .red {background:#ee0000;}  
  114. .graph .green {background:#00cc00;}  
  115. .graph .brown {background:#8B4513;}  
  116.  </style>  
  117.  <!--[if lt IE 9]><script type="text/javascript" defer="defer">  
  118.  window.onload=function(){var i,t=document.getElementsByTagName('table');for(i=0;i<t.length;i++){if(t[i].parentNode.className=='graph')t[i].style.height=150-(t[i].clientHeight-150)+'px';}}  
  119.  </script><![endif]-->   
  120.  </head>  
  121.   
  122.   
  123.  <body>  
  124.  <div class="center">  
  125.   
  126.   
  127.  <h1><a href="?">Opcache Control Panel</a></h1>  
  128.   
  129.   
  130.  <div class="buttons">  
  131. <a href="?ALL=1">Details</a>  
  132. <a href="?FILES=1&GROUP=2&SORT=3">Files</a>  
  133. <a href="?RESET=1" onclick="return confirm('RESET cache ?')">Reset</a>  
  134. <?php if ( function_exists(CACHEPREFIX.'invalidate') ) { ?>  
  135. <a href="?RECHECK=1" onclick="return confirm('Recheck all files in the cache ?')">Recheck</a>  
  136. <?php } ?>  
  137. <a href="?" onclick="window.location.reload(true); return false">Refresh</a>  
  138.  </div>  
  139.   
  140.   
  141.  <?php   
  142.   
  143.   
  144.  if ( !function_exists(CACHEPREFIX.'get_status') ) { echo '<h2>Opcache not detected?</h2>'die; }  
  145.   
  146.   
  147.  if ( !empty($_GET['FILES']) ) { echo '<h2>files cached</h2>'; files_display(); echo '</div></body></html>'exit; }  
  148.   
  149.   
  150.  if ( !(isset($_REQUEST['GRAPHS']) && !$_REQUEST['GRAPHS']) && CACHEPREFIX=='opcache_') { graphs_display(); if ( !empty($_REQUEST['GRAPHS']) ) { exit; } }  
  151.   
  152.   
  153.  ob_start(); phpinfo(8); $phpinfo = ob_get_contents(); ob_end_clean();   
  154. // some info is only available via phpinfo? sadly buffering capture has to be used  
  155.  if ( !preg_match( '/module\_Zend (Optimizer\+|OPcache).+?(\<table[^>]*\>.+?\<\/table\>).+?(\<table[^>]*\>.+?\<\/table\>)/s'$phpinfo$opcache) ) { }  // todo  
  156.   
  157.   
  158.  if ( function_exists(CACHEPREFIX.'get_configuration') ) { echo '<h2>general</h2>'$configuration=call_user_func(CACHEPREFIX.'get_configuration'); }  
  159.   
  160.   
  161.  $host=function_exists('gethostname')?@gethostname():@php_uname('n'); if (empty($host)) { $host=empty($_SERVER['SERVER_NAME'])?$_SERVER['HOST_NAME']:$_SERVER['SERVER_NAME']; }  
  162.  $version=array('Host'=>$host);  
  163.  $version['PHP Version']='PHP '.(defined('PHP_VERSION')?PHP_VERSION:'???').' '.(defined('PHP_SAPI')?PHP_SAPI:'').' '.(defined('PHP_OS')?' '.PHP_OS:'');  
  164.  $version['Opcache Version']=empty($configuration['version']['version'])?'???':$configuration['version'][CACHEPREFIX.'product_name'].' '.$configuration['version']['version'];   
  165.  print_table($version);  
  166.   
  167.   
  168.  if ( !empty($opcache[2]) ) { echo preg_replace('/\<tr\>\<td class\="e"\>[^>]+\<\/td\>\<td class\="v"\>[0-9\,\. ]+\<\/td\>\<\/tr\>/','',$opcache[2]); }  
  169.   
  170.   
  171.  if ( function_exists(CACHEPREFIX.'get_status') && $status=call_user_func(CACHEPREFIX.'get_status') ) {  
  172. $uptime=array();  
  173. if ( !empty($status[CACHEPREFIX.'statistics']['start_time']) ) {   
  174. $uptime['uptime']=time_since($time,$status[CACHEPREFIX.'statistics']['start_time'],1,'');  
  175. }  
  176. if ( !empty($status[CACHEPREFIX.'statistics']['last_restart_time']) ) {   
  177. $uptime['last_restart']=time_since($time,$status[CACHEPREFIX.'statistics']['last_restart_time']);   
  178. }  
  179. if (!empty($uptime)) {print_table($uptime);}  
  180.   
  181. if ( !empty($status['cache_full']) ) { $status['memory_usage']['cache_full']=$status['cache_full']; }  
  182.   
  183. echo '<h2 id="memory">memory</h2>';  
  184. print_table($status['memory_usage']);  
  185. unset($status[CACHEPREFIX.'statistics']['start_time'],$status[CACHEPREFIX.'statistics']['last_restart_time']);  
  186. echo '<h2 id="statistics">statistics</h2>';  
  187. print_table($status[CACHEPREFIX.'statistics']);  
  188.  }  
  189.   
  190.   
  191.  if ( empty($_GET['ALL']) ) { meta_display(); exit; }  
  192.      
  193.  if ( !empty($configuration['blacklist']) ) { echo '<h2 id="blacklist">blacklist</h2>'; print_table($configuration['blacklist']); }  
  194.   
  195.   
  196.  if ( !empty($opcache[3]) ) { echo '<h2 id="runtime">runtime</h2>'echo $opcache[3]; }  
  197.   
  198.   
  199.  $name='zend opcache'$functions=get_extension_funcs($name);   
  200.  if (!$functions) { $name='zend optimizer+'$functions=get_extension_funcs($name); }  
  201.  if ($functions) { echo '<h2 id="functions">functions</h2>'; print_table($functions);  } else { $name=''; }  
  202.   
  203.   
  204.  $level=trim(CACHEPREFIX,'_').'.optimization_level';  
  205.  if (isset($configuration['directives'][$level])) {  
  206. echo '<h2 id="optimization">optimization levels</h2>';  
  207.   
  208. $levelset=strrev(base_convert($configuration['directives'][$level], 10, 2));  
  209. $levels=array(  
  210.      1=>'<a href="http://wikipedia.org/wiki/Common_subexpression_elimination">Constants subexpressions elimination</a> (CSE) true, false, null, etc.<br />Optimize series of ADD_STRING / ADD_CHAR<br />Convert CAST(IS_BOOL,x) into BOOL(x)<br />Convert <a href="http://www.php.net/manual/internals2.opcodes.init-fcall-by-name.php">INIT_FCALL_BY_NAME</a> + <a href="http://www.php.net/manual/internals2.opcodes.do-fcall-by-name.php">DO_FCALL_BY_NAME</a> into <a href="http://www.php.net/manual/internals2.opcodes.do-fcall.php">DO_FCALL</a>',  
  211.      2=>'Convert constant operands to expected types<br />Convert conditional <a href="http://php.net/manual/internals2.opcodes.jmp.php">JMP</a>  with constant operands<br />Optimize static <a href="http://php.net/manual/internals2.opcodes.brk.php">BRK</a> and <a href="<a href="http://php.net/manual/internals2.opcodes.cont.php">CONT</a>',  
  212.      3=>'Convert $a = $a + expr into $a += expr<br />Convert $a++ into ++$a<br />Optimize series of <a href="http://php.net/manual/internals2.opcodes.jmp.php">JMP</a>',  
  213.      4=>'PRINT and ECHO optimization (<a href="https://github.com/zend-dev/ZendOptimizerPlus/issues/73">defunct</a>)',  
  214. 5=>'Block Optimization - most expensive pass<br />Performs many different optimization patterns based on <a href="http://wikipedia.org/wiki/Control_flow_graph">control flow graph</a> (CFG)',  
  215. 9=>'Optimize <a href="http://wikipedia.org/wiki/Register_allocation">register allocation</a> (allows re-usage of temporary variables)',  
  216. 10=>'Remove NOPs'  
  217. );  
  218. echo '<table width="600" border="0" cellpadding="3"><tbody><tr class="h"><th>Pass</th><th>Description</th></tr>';  
  219. foreach ($levels as $pass=>$description) {  
  220. $disabled=substr($levelset,$pass-1,1)!=='1' || $pass==4 ? ' white':'';  
  221. echo '<tr><td class="v center middle'.$disabled.'">'.$pass.'</td><td class="v'.$disabled.'">'.$description.'</td></tr>';  
  222. }  
  223. echo '</table>';  
  224.  }  
  225.   
  226.   
  227.  if ( isset($_GET['DUMP']) ) {   
  228. if ($name) { echo '<h2 id="ini">ini</h2>'; print_table(ini_get_all($name,true)); }   
  229. foreach ($configuration as $key=>$value) { echo '<h2>',$key,'</h2>'; print_table($configuration[$key]); }   
  230. exit;  
  231.  }  
  232.   
  233.   
  234.  meta_display();  
  235.   
  236.   
  237.  echo '</div></body></html>';  
  238.   
  239.   
  240.  exit;  
  241.   
  242.   
  243.  function time_since($time,$original,$extended=0,$text='ago') {  
  244.   
  245. $time =  $time - $original;   
  246. $day = $extendedfloor($time/86400) : round($time/86400,0);   
  247. $amount=0; $unit='';  
  248. if ( $time < 86400) {  
  249. if ( $time < 60)  
  250. $amount=$time$unit='second'; }  
  251. elseif ( $time < 3600) { $amount=floor($time/60); $unit='minute'; }  
  252. else { $amount=floor($time/3600); $unit='hour'; }  
  253.   
  254. }   
  255. elseif ( $day < 14)   
  256. $amount=$day$unit='day'; }  
  257. elseif ( $day < 56)   
  258. $amount=floor($day/7); $unit='week'; }  
  259. elseif ( $day < 672) { $amount=floor($day/30); $unit='month'; }  
  260. else {   $amount=intval(2*($day/365))/2; $unit='year'; }  
  261.   
  262. if ( $amount!=1) {$unit.='s';}  
  263.   
  264. if ($extended && $time>60) { $text=' and '.time_since($time,$time<86400?($time<3600?$amount*60:$amount*3600):$day*86400,0,'').$text; }  
  265.   
  266. return $amount.' '.$unit.' '.$text;  
  267.  }  
  268.   
  269.   
  270.  function print_table($array,$headers=false) {  
  271. if ( empty($array) || !is_array($array) ) {return;}   
  272.    echo '<table border="0" cellpadding="3" width="600">';  
  273.    if (!empty($headers)) {  
  274.    if (!is_array($headers)) {$headers=array_keys(reset($array));}  
  275.    echo '<tr class="h">';  
  276.    foreach ($headers as $value) { echo '<th>',$value,'</th>'; }  
  277.    echo '</tr>';    
  278.   
  279.    }  
  280.    foreach ($array as $key=>$value) {  
  281.      echo '<tr>';  
  282.      if ( !is_numeric($key) ) {   
  283.        $key=ucwords(str_replace('_',' ',$key));  
  284.        echo '<td class="e">',$key,'</td>';   
  285.        if ( is_numeric($value) ) {  
  286.          if ( $value>1048576) { $value=round($value/1048576,1).'M'; }  
  287.          elseif ( is_float($value) ) { $value=round($value,1); }  
  288.        }  
  289.      }  
  290.      if ( is_array($value) ) {  
  291.        foreach ($value as $column) {  
  292.            echo '<td class="v">',$column,'</td>';  
  293.        }  
  294.        echo '</tr>';  
  295.      }  
  296.      else { echo '<td class="v">',$value,'</td></tr>'; }   
  297. }  
  298.    echo '</table>';  
  299.  }  
  300.   
  301.   
  302.  function files_display() {   
  303. $status=call_user_func(CACHEPREFIX.'get_status');  
  304. if ( empty($status['scripts']) ) {return;}  
  305. if ( isset($_GET['DUMP']) ) { print_table($status['scripts']); exit;}  
  306.      $time=time(); $sort=0;   
  307. $nogroup=preg_replace('/\&?GROUP\=[\-0-9]+/','',$_SERVER['REQUEST_URI']);  
  308. $nosort=preg_replace('/\&?SORT\=[\-0-9]+/','',$_SERVER['REQUEST_URI']);  
  309. $group=empty($_GET['GROUP'])?0:intval($_GET['GROUP']); if ( $group<0 || $group>9) { $group=1;}  
  310. $groupset=array_fill(0,9,''); $groupset[$group]=' class="b" ';  
  311.   
  312. echo '<div class="meta">  
  313.   
  314. <a ',$groupset[0],'href="',$nogroup,'">ungroup</a> |   
  315. <a ',$groupset[1],'href="',$nogroup,'&GROUP=1">1</a> |   
  316. <a ',$groupset[2],'href="',$nogroup,'&GROUP=2">2</a> |   
  317. <a ',$groupset[3],'href="',$nogroup,'&GROUP=3">3</a> |   
  318. <a ',$groupset[4],'href="',$nogroup,'&GROUP=4">4</a> |   
  319. <a ',$groupset[5],'href="',$nogroup,'&GROUP=5">5</a>   
  320. </div>';  
  321.   
  322. if ( !$group ) { $files =& $status['scripts']; }  
  323. else {    
  324. $files=array();   
  325. foreach ($status['scripts'as $data) {   
  326. if ( preg_match('@^[/]([^/]+[/]){'.$group.'}@',$data['full_path'],$path) ) {   
  327. if ( empty($files[$path[0]])) { $files[$path[0]]=array('full_path'=>'','files'=>0,'hits'=>0,'memory_consumption'=>0,'last_used_timestamp'=>'','timestamp'=>''); }  
  328. $files[$path[0]]['full_path']=$path[0];  
  329. $files[$path[0]]['files']++;  
  330. $files[$path[0]]['memory_consumption']+=$data['memory_consumption'];  
  331.   
  332. $files[$path[0]]['hits']+=$data['hits'];  
  333. if ( $data['last_used_timestamp']>$files[$path[0]]['last_used_timestamp']) {$files[$path[0]]['last_used_timestamp']=$data['last_used_timestamp'];}  
  334. if ( $data['timestamp']>$files[$path[0]]['timestamp']) {$files[$path[0]]['timestamp']=$data['timestamp'];}  
  335.   
  336. }   
  337. }  
  338. }  
  339.   
  340. if ( !empty($_GET['SORT']) ) {  
  341. $keys=array(  
  342. 'full_path'=>SORT_STRING,  
  343. 'files'=>SORT_NUMERIC,  
  344. 'memory_consumption'=>SORT_NUMERIC,  
  345. 'hits'=>SORT_NUMERIC,  
  346. 'last_used_timestamp'=>SORT_NUMERIC,  
  347. 'timestamp'=>SORT_NUMERIC  
  348. );  
  349. $titles=array('','path',$group?'files':'','size','hits','last used','created');  
  350. $offsets=array_keys($keys);  
  351. $key=intval($_GET['SORT']);  
  352. $direction=$key>0?1:-1;  
  353. $key=abs($key)-1;  
  354. $key=isset($offsets[$key])&&!($key==1&&empty($group))?$offsets[$key]:reset($offsets);  
  355. $sort=array_search($key,$offsets)+1;  
  356. $sortflip=range(0,7); $sortflip[$sort]=-$direction*$sort;  
  357. if ( $keys[$key]==SORT_STRING) {$direction=-$direction; }  
  358. $arrow=array_fill(0,7,''); $arrow[$sort]=$direction>0?' ▼':' ▲';  
  359. $direction=$direction>0?SORT_DESC:SORT_ASC;  
  360. $column=array(); foreach ($files as $data) { $column[]=$data[$key]; }  
  361. array_multisort($column$keys[$key], $direction$files);  
  362. }  
  363.   
  364.   
  365. echo '<table border="0" cellpadding="3" width="960" id="files">  
  366.            <tr class="h">';  
  367.           foreach ($titles as $column=>$title) {  
  368.            if ($titleecho '<th><a href="',$nosort,'&SORT=',$sortflip[$column],'">',$title,$arrow[$column],'</a></th>';  
  369.           }  
  370.           echo ' </tr>';  
  371.      foreach ($files as $data) {  
  372.      echo '<tr>  
  373.      <td class="v" nowrap><a title="recheck" href="?RECHECK=',rawurlencode($data['full_path']),'">x</a>',$data['full_path'],'</td>',  
  374.        ($group?'<td class="vr">'.number_format($data['files']).'</td>':''),  
  375.            '<td class="vr">',number_format(round($data['memory_consumption']/1024)),'K</td>',  
  376.            '<td class="vr">',number_format($data['hits']),'</td>',                
  377.   
  378.            '<td class="vr">',time_since($time,$data['last_used_timestamp']),'</td>',  
  379.            '<td class="vr">',empty($data['timestamp'])?'':time_since($time,$data['timestamp']),'</td>  
  380.            </tr>';  
  381. }  
  382. echo '</table>';  
  383.  }  
  384.   
  385.   
  386.  function graphs_display() {  
  387. $graphs=array();  
  388. $colors=array('green','brown','red');  
  389. $primes=array(223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987);  
  390. $configuration=call_user_func(CACHEPREFIX.'get_configuration');   
  391. $status=call_user_func(CACHEPREFIX.'get_status');  
  392.   
  393.   
  394. $graphs['memory']['total']=$configuration['directives']['opcache.memory_consumption'];  
  395. $graphs['memory']['free']=$status['memory_usage']['free_memory'];  
  396. $graphs['memory']['used']=$status['memory_usage']['used_memory'];  
  397. $graphs['memory']['wasted']=$status['memory_usage']['wasted_memory'];  
  398.   
  399.   
  400. $graphs['keys']['total']=$status[CACHEPREFIX.'statistics']['max_cached_keys'];  
  401.   
  402. foreach ($primes as $prime) { if ($prime>=$graphs['keys']['total']) { $graphs['keys']['total']=$primebreak;} }  
  403. $graphs['keys']['free']=$graphs['keys']['total']-$status[CACHEPREFIX.'statistics']['num_cached_keys'];  
  404. $graphs['keys']['scripts']=$status[CACHEPREFIX.'statistics']['num_cached_scripts'];  
  405. $graphs['keys']['wasted']=$status[CACHEPREFIX.'statistics']['num_cached_keys']-$status[CACHEPREFIX.'statistics']['num_cached_scripts'];  
  406.   
  407.   
  408. $graphs['hits']['total']=0;  
  409. $graphs['hits']['hits']=$status[CACHEPREFIX.'statistics']['hits'];  
  410. $graphs['hits']['misses']=$status[CACHEPREFIX.'statistics']['misses'];  
  411. $graphs['hits']['blacklist']=$status[CACHEPREFIX.'statistics']['blacklist_misses'];  
  412. $graphs['hits']['total']=array_sum($graphs['hits']);  
  413.   
  414.   
  415. $graphs['restarts']['total']=0;  
  416. $graphs['restarts']['manual']=$status[CACHEPREFIX.'statistics']['manual_restarts'];  
  417. $graphs['restarts']['keys']=$status[CACHEPREFIX.'statistics']['hash_restarts'];  
  418. $graphs['restarts']['memory']=$status[CACHEPREFIX.'statistics']['oom_restarts'];  
  419. $graphs['restarts']['total']=array_sum($graphs['restarts']);  
  420.   
  421.   
  422. foreach ( $graphs as $caption=>$graph) {  
  423. echo '<div class="graph"><div class="h">',$caption,'</div><table border="0" cellpadding="0" cellspacing="0">';  
  424.   
  425. foreach ($graph as $label=>$value) {  
  426. if ($label=='total') { $key=0; $total=$value$totaldisplay='<td rowspan="3" class="total"><span>'.($total>999999?round($total/1024/1024).'M':($total>9999?round($total/1024).'K':$total)).'</span><div></div></td>'continue;}  
  427. $percent=$total?floor($value*100/$total):''$percent=!$percent||$percent>99?'':$percent.'%';  
  428. echo '<tr>',$totaldisplay,'<td class="actual">', ($value>999999?round($value/1024/1024).'M':($value>9999?round($value/1024).'K':$value)),'</td><td class="bar ',$colors[$key],'" height="',$percent,'">',$percent,'</td><td>',$label,'</td></tr>';  
  429. $key++; $totaldisplay='';  
  430. }  
  431. echo '</table></div>',"\n";  
  432. }  
  433.  }  
  434.   
  435.   
  436.  function meta_display() {  
  437.  ?>  
  438.  <div class="meta">  
  439. <a href="http://files.zend.com/help/Zend-Server-6/content/zendoptimizerplus.html">directives guide</a> |   
  440. <a href="http://files.zend.com/help/Zend-Server-6/content/zend_optimizer+_-_php_api.htm">functions guide</a> |   
  441. <a href="https://wiki.php.net/rfc/optimizerplus">wiki.php.net</a> |  
  442. <a href="http://pecl.php.net/package/ZendOpcache">pecl</a> |   
  443. <a href="https://github.com/zend-dev/ZendOptimizerPlus/">Zend source</a> |   
  444. <a href="https://gist.github.com/ck-on/4959032/?ocp.php">OCP latest</a>  
  445.  </div>  
  446.  <?php  
  447.  }  
  448.  ?>  




原创粉丝点击